Dbms Lab Manual
Dbms Lab Manual
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.
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:
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> 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)
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.
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.
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:
1. NOT NULL:
Not null constraint at column level.
Syntax:
<col><datatype>(size) not null
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)
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)
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 ) );
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
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
Output:
1 row(s) inserted
3. Select the table:
Query:
SELECT * FROM itstudent;
Output:
SQL> SELECT * FROM itstudent;
Query:
SELECT itstudent.studentID, itstudent.sname,placement.company,
placement.salary FROM itstudent
INNER 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:
Description:
if m=rev
then
dbms_output.put_line('number is palindrome');
else
dbms_output.put_line('number is not palindrome');
end if;
end;
/
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;
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
UPDATE EMP
SET SALARY=UPDATED_SAL
WHERE E_ID=EID;
UPDATE EMP
SET SALARY=UPDATED_SAL
WHERE E_ID=EID;
ELSE
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
BEGIN
CASE grade
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 = {
if job_title in job_salary_ranges:
raise BELOW_SALARY_RANGE(f"The salary for a {job_title} is below the range. Minimum salary is
{min_salary}.")
raise ABOVE_SALARY_RANGE(f"The salary for a {job_title} is above the range. Maximum salary is
{max_salary}.")
else:
# Example usage:
try:
job_title = "Engineer"
salary = 55000
check_salary_range(job_title, salary)
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;
9B. Write a PL/SQL block that reverses the given number using Functions.
--PROCEDURE
create or replace procedure p_add(n1 in int,n2 in int,result out int)
as
begin
result :=n1+n2;
end;
--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;
OUTPUT−
Minimum of (23, 45) : 23
PL/SQL procedure successfully completed.
--PROCEDURE
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
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.
---
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);