0% found this document useful (0 votes)
2 views

Dbms Lab Manual

The document outlines the design and analysis of an ER Model for a Library Management System, detailing entities such as staff, readers, books, publishers, and their relationships. It includes SQL commands for Data Definition Language (DDL) and Data Manipulation Language (DML), demonstrating how to create, alter, drop, and manipulate tables while implementing various integrity constraints. The document also covers group functions using aggregate operators, showcasing how to perform operations like counting employee names.

Uploaded by

kottamsrikanth08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Dbms Lab Manual

The document outlines the design and analysis of an ER Model for a Library Management System, detailing entities such as staff, readers, books, publishers, and their relationships. It includes SQL commands for Data Definition Language (DDL) and Data Manipulation Language (DML), demonstrating how to create, alter, drop, and manipulate tables while implementing various integrity constraints. The document also covers group functions using aggregate operators, showcasing how to perform operations like counting employee names.

Uploaded by

kottamsrikanth08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Design and analyze an ER Model for the following use case.

The Library Management System database keeps track of readers with


the following considerations –.

 The system keeps track of the staff with a single point


authentication system comprising login Id and password.
 Staff maintains the book catalog with its ISBN, Book title, price(in
INR), category(novel, general, story), edition, author Number and
details.
 A publisher has publisher Id, Year when the book was published,
and name of the book.
 Readers are registered with their user_id, email, name (first name,
last name), Phone no (multiple entries allowed), communication
address. The staff keeps track of readers.
Choose appropriate Entities and attributes and relationships and draw the
complete ER diagram.
ER Diagram of Library Management System
This Library ER diagram illustrates key information about the Library,
including entities such as staff, readers, books, publishers, reports, and
authentication system. It allows for understanding the relationships
between entities.

Entities and their Attributes –

 Book Entity : It has authno, isbn number, title, edition, category,


price. ISBN is the Primary Key for Book Entity.
 Reader Entity : It has UserId, Email, address, phone no, name.
Name is composite attribute of firstname and lastname. Phone no is
multi valued attribute. UserId is the Primary Key for Readers entity.
 Publisher Entity : It has PublisherId, Year of publication, name.
PublisherID is the Primary Key.
 Authentication System Entity : It has LoginId and password with
LoginID as Primary Key.
 Reports Entity : It has UserId, Reg_no, Book_no, Issue/Return date.
Reg_no is the Primary Key of reports entity.
 Staff Entity : It has name and staff_id with staff_id as Primary Key.
 Reserve/Return Relationship Set : It has three attributes: Reserve
date, Due date, Return date.
Relationships between Entities –

 A reader can reserve N books but one book can be reserved by only
one reader. The relationship 1:N.
 A publisher can publish many books but a book is published by only
one publisher. The relationship 1:N.
 Staff keeps track of readers. The relationship is M:N.
 Staff maintains multiple reports. The relationship 1:N.
 Staff maintains multiple Books. The relationship 1:N.
 Authentication system provides login to multiple staffs. The relation
is 1:N.
AIM:
Implement Data Definition Language commands -Create, Alter, Drop, Truncate, and Rename.
1. CREATE :
Purpose:
To create a table in the database.
Syntax:
• Create table <table name> (column definition);
Using primary key:
• Create table <table name>
(column 1 datatype NULL/ not NULL,column 2 datatype NULL/not NULL-----------, Constraint
constraint_name primary key column 1,column2,- -(column –n));
EXAMPLE QUERIES:
a. Create a table called employee with following attributes.
i. Employee no
ii. Employee name
iii. Department number
SQL>create table employee(eno number(3),ename varchar2(20),dno number(3));

OUTPUT:
Table created.

b. Create a table called supplier with following attributes.


i. Supplier_id
ii. Supplier_name
iii. Contact_number
iv. Set supplier_id as a primary key
SQL>Create table supplier(supplier_id numeric(10),not NULL,supplier_name varchar2(50)not NULL,
contact_no number(10), constraint supplier_PK PRIMARY KEY(supplier_id));
OUTPUT:
Table created.

2. DESC:
Purpose:
To display the table structure.
Syntax:
• Desc<table name>
EXAMPLE QUERIES:
Command to give the structure of the employee table.
SQL> desc employee.
OUTPUT:
NAME NULL? TYPE
------------ ------- -----------
ENO NUMBER(3)
ENAME VARCHAR2(20)
DNO NUMBER(3)

3.ALTER:
Purpose:
To alter the structure of the table in the database.
Syntax:

• Alter table <tablename>modify(column definitions);


EXAMPLE QUERIES:
Command to modify a field called employee name in employee table.
SQL>alter table employee modify(ename varchar2(30));
OUTPUT:
Table altered.

SQL>desc employee.

OUTPUT:
NAME NULL? Type
----------- --------------------------
ENO NUMBER(3)
ENAME VARCHAR2(30)
DNO NUMBER(3)
EXAMPLE QUERIES:
Command to modify the data type of the field ENO.
SQL>alter table employee modify(eno number(5));
OUTPUT:
Table created.
SQL>desc employee;
NAME NULL? TYPE
----------- --------------------------
ENO NUMBER(5)
ENAME VARCHAR2(30)
DNO NUMBER(3)
SAL NUMBER(12,2)

• Alter table<table name> add(column definitions);


EXAMPLE QUERIES:
Command to add a field called salary in employee table.
SQL>alter table employee add(sal number(12,2));
OUTPUT:
Table created .
SQL>desc employee;

NAME NULL? TYPE


----------- --------------------------
ENO NUMBER(3)
ENAME VARCHAR2(30)
DNO NUMBER(3)
SAL NUMBER(12,2)
DNAME VARCHAR2(20)

• Alter table <table name> rename column<old column name>to<new column name>
EXAMPLE QUERIES:
Command to rename the column name
SQL>alter table employee rename column ename to empname.
OUTPUT:
Table altered.
SQL>desc employee;
NAME NULL? TYPE
----------- --------------------------
ENO NUMBER(5)
EMPNAME VARCHAR2(30)
DNO NUMBER(3)
SAL NUMBER(12,2)

• Alter table <table name>add constraint name>primary key(column 1, column2.....,column n-1);


EXAMPLE QUERIES:
SQL>alter table employee add constraint pk primary key (eno);
OUTPUT:
Table altered.
SQL>desc employee;
NAME NULL? TYPE
----------- --------------------------
ENO NOT NULL NUMBER(5)
EMPNAME VARCHAR2(30)
DNO NUMBER(3)
SAL NUMBER(12,2)

• Alter table<table name>drop column<column name>;


EXAMPLE QUERIES:
SQL>alter table employee drop column dno;
OUTPUT:
table altered.
SQL>desc employee;
NAME NULL? TYPE
----------- --------------------------
ENO NOT NULL NUMBER(5)
EMPNAME VARCHAR2(30)
SAL NUMBER(12,2)

• Alter table <table name>drop constraint<constraint name>;


EXAMPLE QUERIES:
SQL> alter table employee drop constraint pk;
OUTPUT:
Table altered.
SQL>desc employee;
NAME NULL? TYPE
----------- --------------------------
ENO NUMBER(5)
EMPNAME VARCHAR2(30)
SAL NUMBER(12,2)

• Alter table <table name> rename to<table name>;


EXAMPLE QUERIES:
Command to rename the table name
SQL> alter table employee rename to emp;
OUTPUT:
Table altered.
SQL> desc employee
OUTPUT:
ERROR:
ORA-04043: object sample does not exist
SQL> desc emp
OUTPUT:
NAME NULL? TYPE
----------- --------------------------
ENO NUMBER(5)
EMPNAME VARCHAR2(30)
DNO NUMBER(3)
SAL NUMBER(12,2)

4. DROP:
Purpose:
To remove the table from the database.
Syntax:
• Drop table<table name>
EXAMPLE QUERIES:
Command to drop the employee table
SQL>drop table employee.
OUTPUT:
Table droped.
SQL> desc employee
ERROR:
ORA-04043: object employee does not exist

5.TRUNCATE:
Purpose:
To remove the entire content of the table from the database.
Syntax:
• Truncate table<table name>
EXAMPLE QUERIES:
SQL>truncate table employee
OUTPUT:
Table truncated.
SQL>select *from employee;
no rows selected.

Result:
Thus, the DDL commands are executed.
Aim:
Implement Data Manipulation Language commands - Insert, Select, Update, and Delete.

1. INSERT:
Purpose:
To add records to the table
Syntax:
a.Direct method-
only one record can be inserted in the field at a time
• Insert into<table name>values<values for all columns>;
Example queries:
insert into employee values(3,'Brindha',123,9100,'CSE');
OUTPUT:
1 row inserted.

b.Null method-
we can skip some field
• Insert into<table name>(column name)values(values for columns);
Example queries:
insert into employee(eno,sal) values(11,5000);
OUTPUT:
1 row inserted.

c.Macro method-
More than one value can be inserted in the field at a time.
• Insert into<table name>values<&column names>;
Example queries:
Command to insert records into employee table.
SQL >.insert into employee values ( &eno, ’&ename’ ,&dno ,&sal, ‘&dname’); Enter value for eno:1
Enter value for ename:D.Abinaya
Enter the value for dno:111
Enter the value sal:8000
Enter the value for dname:IT
Old 1:insert into employee values(&eno,’&ename’,&dno,&sal,’&dname’ New 1:insert into employee
values(1,’D.Abinaya’,111,8000,’IT’)
Output:
1 row created
To execute the command which is in buffer
SQL>/
Enter value for eno:2
Enter value for ename: P.Ratha
Enter value for dno:111
Enter value for sal:8900
Enter value for dname:IT
Old 1: insert into employee values (&eno,’&ename’,&dno,&sal,’&dname’); New 1: insert into
employee values (2,’P.Ratha’,111,8900,’IT’)
Output:
1 row created
2. SELECT:
Purpose: Syntax:
To retrieve or view records with in the table
Syntax:
• Select * from<table name>
Example queries:
select * from employee;
Output:
ENO ENAME DNO SAL DNAME
---------------------------------------------
1 Abinaya111 8000 IT
2 P.Ratha 111 8900 IT
3 Brindha 123 9100 CSE
4 Ajay 123 9110 CSE
5 Indira 145 7500 AI
6 Adhi 145 7900 AI
8 Harsha 132 9900 EIE
9 Mithuna 133 8900 EIE
10 Sahana 133 9990 EIE
11 5000

10 rows selected.
• Select *from <table name> where(condition)
Example queries:
Display enmae,dno from employee where sal>9000.
SQL>Select ename,dno from employee where sal>9000;
Output:
ENAME DNO
-----------------
Brindha 123
Ajay 123
Harsha 132
Sahana 133
4 rows selected.
• Select (column name) from<table name>
Example queries:
Find out the names of all the employees
SQL>select ename from employee;
Output:
ENAME
---------------
D.Abinaya
P.Ratha
Brindha
Ajay
Indira
Adhi
Harsha
Mithuna
Sahana
10 rows selected
3. UPDATE:
Purpose:
To modify records with in the table
Syntax:
• Update<table name>set(column name)=(value)where(condition)
Example queries:
SQL> update employee set ename='Raju' where eno=11;
OUTPUT:
1 row updated.

• Update<table name>set(column name)=(value);


Example queries:
updating all values of the column
SQL> update employee set sal=9000;
OUTPUT:
11 rows updated.

4. DELETE:
Purpose:
To modify records from a table.
Syntax:
• Delete from<table name>where(condition)
Example queries:
Delete a specific record from the table.
SQL> delete from employee where ename='Ajay';
OUTPUT:
1 row deleted.

• Delete from<table name>


Example queries:
Delete all rows in a table without deleting the table
SQL> delete from employee;
OUTPUT:
10 rows deleted.

Result:
Thus, DML Queries were executed.
AIM:
Implement various types of integrity constraints - NOT NULL constraint,
DEFAULT constraint, UNIQUE constraint, PRIMARY key, FOREIGN key,
CHECK constraint.

PROCEDURE:

Create table by using Constraints:


Constraints are two types:
1. Table Level Constraints.
2. Column Level Constraints.

1. NOT NULL:
 Not null constraint at column level.
Syntax:
<col><datatype>(size) not null

SQL > create table emp


(
e_id varchar2(5) NOT NULL,
e_name varchar2(10),
e_design varchar2(10),
dept varchar2(10),
mgr varchar2(10),
salary number(10));
OUTPUT:
Table created.
SQL> desc emp;
Name Null? Type
----------------------------------------- -------- ----------------------------
EID NOT NULL VARCHAR2(5)
ENAME VARCHAR2(10)
EDESIGN VARCHAR2(10)
DEPT VARCHAR2(10)
MGR VARCHAR2(10)
SALARY NUMBER(10)

2. UNIQUE :
 Unique constraint at column level.
Syntax: <col><datatype>(size)unique
Ex:-
SQL > create table depositor
(
customer_name varchar2(10),
acc_no number(15) UNIQUE,
brach_name varchar2(10));
Table created.
SQL> desc depositor
Name Null? Type
----------------------------------------- -------- ----------------------------
CUSTOMER_NAME VARCHAR2(10)
ACC_NO NUMBER(15)
BRACH_NAME VARCHAR2(10)

 Unique constraint at table level:


Syntax:
Create table tablename(col=format,col=format,unique(<col1>,<col2>));
Ex:-
SQL > create table depositor1
(
customer_name varchar2(10),
acc_no number(15),
brach_name varchar2(10),UNIQUE(acc_no));

3. PRIMARY KEY:
 Primary key constraint at column level
Syntax:
<col><datatype>(size)primary key;
Ex:-
SQL> create table customer
(
customer_id number (5) PRIMARY KEY,
customer_name varchar2(10),
customer_street varchar2(10),
brach_name varchar2(10));
SQL> desc customer
Name Null? Type
----------------------------------------- -------- ----------------------------
CUSTOMER_ID NOT NULL NUMBER(5)
CUSTOMER_NAME VARCHAR2(10)
CUSTOMER_STREET VARCHAR2(10)
BRACH_NAME VARCHAR2(10)

 Primary key constraint at table level.


Syntax:
Create table tablename(col=format,col=format primary
key(col1>,<col2>);
Ex:-
SQL > create table customer1
(
customer_id number (5),
customer_name varchar2(10),
customer_street varchar2(10),
brach_name varchar2(10),PRIMARY KEY(customer_id));
4. CHECK:
 Check constraint constraint at column level.
Syntax: <col><datatype>(size) check(<logical expression>)
Ex:-create table loan
(
loan_no varchar2(10),
customer_name varchar2(10),
balance number (10) CHECK(balance>1000));
SQL> desc loan
Name Null? Type
----------------------------------------- -------- ----------------------------
LOAN_NO VARCHAR2(10)
CUSTOMER_NAME VARCHAR2(10)
BALANCE NUMBER(10)
 Check constraint constraint at table level.
Syntax: check(<logical expression>)
Ex:- create table loan1
(loan_no varchar2(10),
customer_name varchar2(10),
balance number (10), CHECK(balance>1000));
SQL> desc loan1
Name Null? Type
----------------------------------------- -------- ----------------------------
LOAN_NO VARCHAR2(10)
CUSTOMER_NAME VARCHAR2(10)
BALANCE NUMBER(10)

5. FOREIGN KEY:
 Foreign key constraint at column level.
Syntax:
Column_name Datatype(size) REFERENCES parent_table_name
(parent_column_name)
Ex:- CREATE TABLE books
(
book_id NUMBER(3),
book_title VARCHAR22(30),
book_price NUMBER(3),
book_author_id NUMBER(3) REFERENCES author(author_id ) );

 Foreign key constraint at table level


Syntax:
CONSTRAINT constraint_name FOREIGN KEY(child_table_column)
REFERENCES
Parent_table_name(parent_table_column)
Ex:-CREATE TABLE books
(
book_id NUMBER(3) CONSTRAINT bok_bi_pk PRIMARY
KEY,
book_title VARCHAR22(30),
book_price NUMBER(3),
book_author_id NUMBER(3),
CONSTRAINT bok_ai_fk FOREIGN KEY (book_author_id) REFERENCES
author(author_id) );
SQL> desc books
Name Null? Type
----------------------------------------- -------- ----------------------------
BOOK_ID NUMBER(3)
BOOK_TITLE VARCHAR2(30)
BOOK_PRICE NUMBER(3)
BOOK_AUTHOR_ID NUMBER(3)

RESULT:
Thus, integrity constraints were executed.
AIM:
Implement group functions with different operators such as aggregate
operators, group by, having and order by.

PROCEDURE:
(i) Create Employee table containing all Records.
SQL> create table emp(eid number,ename varchar2(10),age
number,salary number);
Table created.
SQL> desc emp;
Name Null? Type
----------------------- -------- ----------------------------
EID NUMBER
ENAME VARCHAR2(10)
AGE NUMBER
SALARY NUMBER

(ii)Count number of employee names from employee table.


SQL> select count(ename) from emp;
COUNT(ENAME)
-------------------------
7
(iii)Find the Maximum age from employee table.
SQL> select max(age) from emp;
MAX(AGE)
-----------------
44
(iv)Find the Minimum age from employee table.
SQL> select min(age) from emp;
MIN(AGE)
----------------
22
(v)Display the Sum of age employee table.
SQL> select sum(age) from emp;
SUM(AGE)
----------------
220
(vi)Display the Average of age from Employee table.
SQL> select avg(age) from emp;
AVG(AGE)
----------------
31.4285714
(vii)Create a View for age in employee table.
SQL> create or replace view A as select age from emp where age<30;
View created.
(viii)Display views
SQL> select * from A;
AGE
-------------
22
29
27
29
(ix)Find grouped salaries of employees.(group by clause)
SQL> select salary from emp group by salary;
SALARY
--------------
9000
10000
8000
6000
7000
(x).Find salaries of employee in Ascending Order.(order by
clause)
SQL> select ename,salary from emp order by salary;
ENAME SALARY
------------ -------------
rohan 6000
alex 7000
shane 8000
abhi 8000
tiger 8000
anu 9000
scott 10000
7 rows selected.
(xi) Find salaries of employee in Descending Order.
SQL> select ename,salary from emp order by salary desc;
ENAME SALARY
-------------- ---------------
scott 10000
anu 9000
shane 8000
abhi 8000
tiger 8000
alex 7000
rohan 6000
7 rows selected.
(xii)Having Clause.
SQL> select ename,salary from emp where age<29 group by
ename,salary having
salary<10000;
ENAME SALARY
----------- --------------
alex 7000
anu 9000
RESULT:
Thus, queries using aggregate functions were executed.
Week 5:a)Creation of views, synonyms, sequence, indexes and save point.
b)Implement various types of joins - outer join and inner join.

5A . Creation of views, synonyms, sequence, indexes and save point.


VIEW
DEFINITION:
A view, is a logical table based on one or more tables or views. A view
contains no data itself. The tables upon which a view is based are called
base tables.
SYNTAX:
CREATE VIEW view_name
AS<Query Expression>
QUERIES:
Query:
create table student(sid number, sname varchar2(10),
department varchar2(5));
Output:
Table created.
Query:
insert into student values(1, 'bala', 'IT');
insert into student values(2, 'rupesh', 'IT');
insert into student values(3, 'sai', 'CSE');
insert into student values(4, 'art', 'CSE');
Output:
4 row(s) inserted
Query:
select * from student;
OUTPUT:

Query:
create view studview as select * from student where
department='IT';
Output:
view created.
Query:
select * from studview;
Output:
SID SNAME DEPARTMENT
1 bala IT
2 rupesh IT

Query:
insert into studview values(7,'art','IT');
Output:
1 row(s) inserted.
Query:
select * from studview;
Output:
SID SNAME DEPARTMENT
1 bala IT
2 rupesh IT
45
1 bala IT
2 rupesh IT
7 art IT

Query:
update studview set sid=10 where sid=7;
Output:
1 row(s) updated.
Query:
select * from studview;
Output:
SID SNAME DEPARTMENT
1 bala IT
2 rupesh IT
10 art IT

Query:
delete from studview where sid = 10;
Output:
1 row(s) deleted
Query:
select * from studview;
Output:
SID SNAME DEPARTMENT
1 bala IT
2 rupesh IT

Query:
drop view studview;
Output:
view dropped.

-------------------

SYNONYM
DEFINITION:
A synonym is an alternative name for objects such as tables, views,
sequences, stored procedures, and other database objects.
SYNTAX
Create Synonym:
Create synonym syn_name for table_name;
Delete Synonym:
Drop synonym syn_name;
QUERIES:
Query:
create synonym stud_syn for student;
Output:
synonym created.
Query:
select * from stud_syn;
Output:
SID SNAME DEPARTMENT
1 bala IT
2 rupesh IT
3 sai CSE
4 art CSE

Query:
insert into stud_syn values(4,'harish','CSE');
Output:
1 row(s) inserted.

Query:
select * from stud_syn;
Output:
SID SNAME DEPARTMENT
1 bala IT
2 rupesh IT
3 sai CSE
4 art CSE
5 harish CSE

Query:
drop synonym stud_syn;
Output:
synonym dropped.

---------------------
SEQUENCES

DEFINITION:
Asequence, is a database object from which multiple users may generate
unique integers. Sequences can be used to automatically generate
primary key values. When a sequence number is generated, the sequence
is incremented, independent of the transaction committing or rolling
back.

SYNTAX:
CREATE SEQUENCE [SEQUENCE NAME]
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}]
[{ORDER n | NOORDER}];
[SEQUENCE NAME] – The Name of the sequence.
[START WITH n] – This clause specifies the starting point of the sequence.
[INCREMENT BY n] – This clause specifies the incremental difference
between the two numbers.
[MAXVALUE n] – This clause specifies the maximum value attainable by the
sequence
[NOMAXVALUE] – This clause is the default specification for Maximum value
of the sequence.
[MINVALUE n] – The clause specifies the minimum value of a sequence.
[NOMINVALUE] – This clause is the default specification of Minimum value of
the sequence.
[CYCLE | NOCYCLE] – This clause adds cyclic behavior to a sequence. The
sequence recycles the values once the MAXVALUE is reached. It is least
relevant if sequence is used as Primary key generator. NOCYCLE is the
default behavior.
[CACHE n| NOCACHE] – This clause directs Oracle server to cache ‘n’ values
of a sequence. Its value is 20 by default. NOCACHE is the default behavior of
the sequence.
[{ORDER n | NOORDER}] – This clause ensures that sequence values are
generated in order. Generally, it is least usable clause in sequence DEFINITION
but they are helpful in applications which use sequence as timestamp value.
All sessions using same sequence share the same cache to fetch the values.
NOORDER is the default behavior of the sequence.
QUERIES:
Query:
CREATE SEQUENCE seq_num
increment by 2
start with 11
minvalue 1
maxvalue 20
cache 20;
Output:
sequence created.
Query:
insert into student values(seq_num.nextval, 'Bala','IT');
Output:
1 row(s) inserted.
Query:
select * from student;
Output:
SID SNAME DEPARTMENT
1 bala IT
2 rupesh IT
3 sai CSE
4 art CSE
5 harish CSE
11 Bala IT

Query:
drop sequence seq_num;
Output:
sequence dropped.

--------------------
INDEXES

DEFINITION:
An index is a performance-tuning method of allowing faster retrieval of
records. An index creates an entry for each value that appears in the
indexed columns.
SYNTAX:
Create index:
CREATE INDEX idx_name ON table_name(attribute);
Drop Index:
DROP INDEX index_name;
QUERIES:

OUTPUT:

Query:
create index idx_stud on student(sid);
Output:
index created.
Query:
drop index idx_stud;
Output:
index dropped.

-----------------

SAVEPOINT

DEFINITION:
SAVEPOINT statement is to identify a point in a transaction to which you
can later roll back.
With the ROLLBACK TO statement, savepoints undo parts of a
transaction instead of the whole transaction.
The RELEASE SAVEPOINT statement removes the named savepoint from
the set of savepoints of the current transaction.
SYNTAX:
SAVEPOINT identifier
ROLLBACK [WORK] TO [SAVEPOINT] identifier
RELEASE SAVEPOINT identifier
QUERIES:
Query:
SAVEPOINT s;
Output:
Savepoint created.
Query:
ROLLBACK TO s;
Query:
select * from emp;

5B. b)Implement various types of joins - outer join and inner join.

JOIN TYPES
1. INNER JOIN
2. OUTER JOIN
a. LEFT OUTER JOIN
b. RIGHT OUTER JOIN
c. FULL OUTER JOIN
3. SELF JOIN
4. EQUI JOIN
5. SELF JOIN

1. Table Creation
Query:
CREATE TABLE itstudent
(
studentID NUMBER PRIMARY KEY,
sname VARCHAR(30),
department CHAR(5),
sem NUMBER
);
Output:
Table Created
Query:
CREATE TABLE placement
(
PlacementID NUMBER PRIMARY KEY,
StudentID NUMBER references itstudent(studentid),
department CHAR(5),
Company VARCHAR2(30),
salary NUMBER
);

Output:
Table Created

2. Insert into the table


Query:
INSERT INTO itstudent VALUES(101,'reema', 'IT',5);
Output:
1 row(s) inserted.
Query:
INSERT INTO itstudent VALUES(102,'reenu', 'IT',3);
Output:
1 row(s) inserted
Query:
INSERT INTO itstudent VALUES(103,'sheela', 'CSE',3);
Output:
1 row(s) inserted
Query:
INSERT INTO itstudent VALUES(104,'nirmal', 'IT',3);
Output:
1 row(s) inserted
Query:
INSERT INTO itstudent VALUES(105,'eshwar', 'CSE',5);
Output:
1 row(s) inserted
Query:
INSERT INTO placement VALUES(1, 104, 'IT', 'infosys', 25000);
Output:
1 row(s) inserted.
Query:
INSERT INTO placement VALUES(2, 105, 'CSE', 'Wipro', 22000);
Output:
1 row(s) inserted
Query:
INSERT INTO placement VALUES(4, 102, 'IT', 'infosys', 25000);
Output:
1 row(s) inserted
Query:
INSERT INTO placement VALUES(5, 103, 'CSE', 'infosys', 25000);

Output:
1 row(s) inserted
3. Select the table:
Query:
SELECT * FROM itstudent;
Output:
SQL> SELECT * FROM itstudent;

STUDENTID SNAME DEPAR SEM


---------- ------------------------------ ----- ----------
101 reema IT 5
102 reenu IT 3
103 sheela CSE 3
104 nirmal IT 3
105 eshwar CSE 5
Query:
SELECT * FROM placement;
Output:
PLACEMENTID STUDENTID DEPAR COMPANY SALARY
----------- ---------- ----- ------------------------------ ----------
1 104 IT infosys 25000
2 105 CSE Wipro 22000
4 102 IT infosys 25000
5 103 CSE infosys 25000
4. INNER JOIN
Query:
SELECT *
FROM itstudent
INNER JOIN Placement
ON itstudent.studentID=placement.StudentID;
Output:

Query:
SELECT itstudent.studentID, itstudent.sname,placement.company,
placement.salary FROM itstudent
INNER JOIN placement
ON itstudent.studentID=placement.studentID;
Output:

5. LEFT OUTER JOIN


Query:
SELECT *
FROM itstudent
LEFT OUTER JOIN placement
ON itstudent.studentID=placement.studentID;
Output:

6. RIGHT OUTER JOIN


Query:
SELECT *
FROM itstudent
RIGHT OUTER JOIN placement
ON itstudent.studentID=placement.studentID;
Output:

7. FULL OUTER JOIN


Query:
SELECT *
FROM itstudent
FULL OUTER JOIN placement
ON itstudent.studentID=placement.studentID;
Output:

8. EQUI JOIN
Query:
SELECT * FROM itstudent, placement WHERE
itstudent.studentID=placement.studentID;
Output:

9. SELF JOIN
Returns rows by comparing the values of the same table.
Query:
CREATE TABLE employee
(
empid NUMBER,
empname VARCHAR2(25),
reportingid NUMBER
);
Output:
Table Created
Query:
INSERT INTO employee VALUES(1, 'Principal', null);
Output:
1 row(s) inserted.
Query:
INSERT INTO employee VALUES(2, 'HOD', 1);
Output:
1 row(s) inserted.
Query:
INSERT INTO employee VALUES(3, 'PO', 1);
Output:
1 row(s) inserted.
Query:
INSERT INTO employee VALUES(4, 'Staff', 2);
Output:
1 row(s) inserted.
Query:
INSERT INTO employee VALUES(5, 'Non Teaching Staff', 2);
Output:
1 row(s) inserted.
Query:
SELECT * FROM employee;
Output:
EMPID EMPNAME REPORTINGID
---------- ------------------------- -----------
1 Principal
2 HOD 1
3 PO 1
4 Staff 2
5 Non Teaching Staff 2
Query:
SELECT e1.empid, e1.empname, e2.empname AS HeadName
FROM employee e1, employee e2
WHERE e1.reportingid=e2.empid;
Output:

EMPID EMPNAME HEADNAME


---------- ------------------------- -------------------------
3 PO Principal
2 HOD Principal
5 Non Teaching Staff HOD
4 Staff HOD
DBMS- Experimental Learning 6

Construct PL/SQL block for the following

6.1 Aim: To determine whether a number is palindrome

Description:

set serveroutput on;


declare
n number;
m number;
rev number:=0;
r number;
begin
n:=12321;
m:=n;
while n>0
loop
r:=mod(n,10);
rev:=(rev*10)+r;
n:=trunc(n/10);
end loop;

if m=rev
then
dbms_output.put_line('number is palindrome');
else
dbms_output.put_line('number is not palindrome');
end if;
end;
/

6.2 Aim: To determine whether a number is Armstrong

declare
n number:=407;
s number:=0;
r number;
len number;
m number;
begin
m:=n;

len:=length(to_char(n));

while n>0
loop
r:=mod(n,10);
s:=s+power(r,len);
n:=trunc(n/10);
end loop;

if m=s
then
dbms_output.put_line('armstrong number');
else
dbms_output.put_line('not armstrong number');
end if;

end;
/

6.3
Aim : To find greatest of three numbers
………………………………………………………………………………
declare
a number:=10;
b number:=12;
c number:=5;
begin
dbms_output.put_line('a='||a||' b='||b||' c='||c);
if a>b AND a>c
then
dbms_output.put_line('a is greatest');
else
if b>a AND b>c
then
dbms_output.put_line('b is greatest');
else
dbms_output.put_line('c is greatest');
end if;
end if;
end;
/

6.4
Aim: To display Fibonacci series

declare
first number:=0;
second number:=1;
third number;
n number:=&n;
i number;

begin
dbms_output.put_line('Fibonacci series is:');
dbms_output.put_line(first);
dbms_output.put_line(second);

for i in 2..n
loop
third:=first+second;
first:=second;
second:=third;
dbms_output.put_line(third);
end loop;
end;
/
SQL> SELECT *FROM EMP;

E_ID E_NAME SALARY

----- ---------- ----------

1 BRI 30000

2 SRI 35000

3 HARI 46000

4 NATRAJ 31000

5 LOKESH 70000

6 SRAVANI 68000

7 SUNI 98000

8 INDIRA 50000

9 HEERA 60000

10 KAVITHA 75000

10 rows selected.

DECLARE

EID EMP.E_ID%TYPE:=10;

NAME EMP.E_NAME%TYPE;

CURRENT_SAL EMP.SALARY%TYPE;

UPDATED_SAL EMP.SALARY%TYPE;

BEGIN
SELECT E_ID,E_NAME,SALARY

INTO EID,NAME,CURRENT_SAL

FROM EMP

WHERE E_ID=EID;

IF CURRENT_SAL<30000 THEN

UPDATED_SAL := CURRENT_SAL * 1.20;

UPDATE EMP

SET SALARY=UPDATED_SAL

WHERE E_ID=EID;

DBMS_OUTPUT.PUT_LINE('Employee ' || EID || ' had a salary of ' ||


CURRENT_SAL || ' and now has a salary of ' || UPDATED_SAL);

ELSIF CURRENT_SAL>30000 AND CURRENT_SAL<60000 THEN

UPDATED_SAL := CURRENT_SAL * 1.10;

UPDATE EMP

SET SALARY=UPDATED_SAL

WHERE E_ID=EID;

DBMS_OUTPUT.PUT_LINE('Employee ' || EID || ' had a salary of ' ||


CURRENT_SAL || ' and now has a salary of ' || UPDATED_SAL);

ELSE

UPDATED_SAL := CURRENT_SAL * 1.05;

UPDATE EMP

SET SALARY=UPDATED_SAL

WHERE E_ID=EID;
DBMS_OUTPUT.PUT_LINE('Employee ' || EID || ' had a salary of ' ||
CURRENT_SAL || ' and now has a salary of ' || UPDATED_SAL);

END IF;

END;

/
EXPERIMENT-7

7b)
Aim:To Write a PL/SQL program to display the decrpition against a
student grade using case statement.

DECLARE

grade char(1) := 'D';

BEGIN

CASE grade

when 'A' then dbms_output.put_line('Excellent');

when 'B' then dbms_output.put_line('Very good');

when 'C' then dbms_output.put_line('Good');

when 'D' then dbms_output.put_line('Average');

when 'F' then dbms_output.put_line('Passed with Grace');

else dbms_output.put_line('Failed');

END CASE;

END;
/
EXCEPTIONS:
b) Construct the user-defined exceptions to get the salary of an employee and check it with
the job’s salary range. If the salary is below the range, raise an exception
BELOW_SALARY_RANGE. If the salary is above the range, raise the exception
ABOVE_SALARY_RANGE.
Define the custom exceptions BELOW_SALARY_RANGE and ABOVE_SALARY_RANGE.

class BELOW_SALARY_RANGE(Exception):

pass

class ABOVE_SALARY_RANGE(Exception):

pass

# Define a dictionary to store job salary ranges (you can modify this as needed)

job_salary_ranges = {

"Engineer": (60000, 90000),

"Manager": (80000, 120000),

"Designer": (50000, 80000)

def check_salary_range(job_title, salary):

if job_title in job_salary_ranges:

min_salary, max_salary = job_salary_ranges[job_title]

if salary < min_salary:

raise BELOW_SALARY_RANGE(f"The salary for a {job_title} is below the range. Minimum salary is
{min_salary}.")

elif salary > max_salary:

raise ABOVE_SALARY_RANGE(f"The salary for a {job_title} is above the range. Maximum salary is
{max_salary}.")
else:

raise ValueError("Invalid job title")

# Example usage:

try:

job_title = "Engineer"

salary = 55000

check_salary_range(job_title, salary)

print(f"The salary for a {job_title} is within the range.")

except BELOW_SALARY_RANGE as e:

print(e)

except ABOVE_SALARY_RANGE as e:

print(e)

except ValueError as e:

print(e)
9A. Write a function that accepts two numbers A and B and performs the
following operations.
o Addition
o Subtraction
o Multiplication
o Division

--addition function
CREATE OR REPLACE FUNCTION addition (
a in NUMBER,
b in NUMBER )
RETURN NUMBER
IS
BEGIN
RETURN a+b ;
END;

--substraction function
CREATE OR REPLACE FUNCTION sub (
a in NUMBER,
b in NUMBER )
RETURN NUMBER
IS
BEGIN
RETURN a-b ;
END;

--multiplication function
CREATE OR REPLACE FUNCTION mul (
a in NUMBER,
b in NUMBER )
RETURN NUMBER
IS
BEGIN
RETURN a*b ;
END;

--division function
CREATE OR REPLACE FUNCTION div (
a in NUMBER,
b in NUMBER )
RETURN NUMBER
IS
BEGIN
RETURN a/b ;
END;

--Main Block of code calling the function


declare
n1 number:=10;
n2 number:=5;
op varchar(10) := '4';
begin
case
when op = '1' then dbms_output.put_line(addition(n1,n2));
when op = '2' then dbms_output.put_line(sub(n1,n2));
when op = '3' then dbms_output.put_line(mul(n1,n2));
when op = '4' then dbms_output.put_line(div(n1,n2));
else dbms_output.put_line('wrong output');
end case;
end;

9B. Write a PL/SQL block that reverses the given number using Functions.

-- Function creation for reverse


create or replace function ReverseNo
return number
Is
n number:=123;
p number;
c number:=0;
begin
while ( n>0)
LOOP
p:=mod(n,10);
c:=c*10+p;
n:=(n-p)/10;
END LOOP;
DBMS_OUTPUT.PUT_LINE('NO IS ' || c);
return c;
end;

--Main Block to call the function


DECLARE
c number(5);
BEGIN
rev := ReverseNo();
dbms_output.put_line('reverse of a number is: ' || rev);
END;
10A. Write a procedure that accepts two numbers and displays their sum.

--PROCEDURE
create or replace procedure p_add(n1 in int,n2 in int,result out int)
as
begin
result :=n1+n2;
end;

--MAIN BLOCK OF CODE TO CALL THE PROCEDURE


declare
result int;
begin
p_add(5,5,result);
dbms_output.put_line(result);
end;

10B. Write procedures to demonstrate IN, IN OUT and OUT parameters.

IN & OUT Mode Example 1


This program finds the minimum of two values. Here, the procedure takes
two numbers using the IN mode and returns their minimum using the OUT
parameters.

--PROCEDURE
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;

--MAIN BLOCK CODE


BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/

OUTPUT−
Minimum of (23, 45) : 23
PL/SQL procedure successfully completed.

IN & OUT Mode Example 2


This procedure computes the square of value of a passed value. This
example shows how we can use the same parameter to accept a value and
then return another result.

--PROCEDURE
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;

--MAIN BLOCK CODE


BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/

When the above code is executed at the SQL prompt, it produces the
following result −
Square of (23): 529
PL/SQL procedure successfully completed.

---

Methods for Passing Parameters


Actual parameters can be passed in three ways −
Positional notation
Named notation
Mixed notation
Positional Notation
In positional notation, you can call the procedure as −
findMin(a, b, c, d);
In positional notation, the first actual parameter is substituted for the first
formal parameter; the second actual parameter is substituted for the second
formal parameter, and so on. So, a is substituted for x, b is substituted for
y, c is substituted for z and d is substituted for m.

Named Notation
In named notation, the actual parameter is associated with the formal
parameter using the arrow symbol ( => ). The procedure call will be like the
following −
findMin(x => a, y => b, z => c, m => d);

Mixed Notation
In mixed notation, you can mix both notations in procedure call; however,
the positional notation should precede the named notation.
The following call is legal −
findMin(a, b, c, m => d);
However, this is not legal:
findMin(x => a, b, c, d);

You might also like