Dbms Complete Lab Manual
Dbms Complete Lab Manual
A Helpful Hand
CSEROCKZ
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
3). Upon successful login you will get SQL prompt (SQL>).
In two ways you can write your programs:
a) directly at SQL prompt (or)
b) in sql editor.
If you type your programs at sql prompt then screen will look
like follow:
SQL> SELECT ename,empno,
2 sal from
3 emp;
where 2 and 3 are the line numbers and rest is the command
/program……
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
This how we can write, edit and execute the sql command and
programs.
Background Theory
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
DDL commands:
Syntax:
Ex:
create table emp(empno number(4) primary key, ename char(10));
Syntax:
Ex:
alter table emp add(sal number(7,2));
Syntax:
Alter table <tablename> drop column <col>;
Ex:
alter table emp drop column sal;
Syntax:
Alter table <tablename> modify(<col><newdatatype>(<newsize>));
Ex:
3
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Syntax:
Ex:
rename emp to emp1;
Syntax:
Ex:
7. Destroying tables.
Syntax:
Ex:
DML commands:
Syntax 1:
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Syntax 2:
Syntax 3:
Ex 1:
Ex 2:
Ex 3:
9. Delete operations.
Syntax:
Syntax:
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp>;
Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp>
where <condition>;
Syntax:
<col><datatype>(size)not null
b) unique constraint
Syntax:
Syntax:
Create table
tablename(col=format,col=format,unique(<col1>,<col2>);
Syntax:
<col><datatype>(size)primary key;
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Syntax:
Syntax:
Syntax:
h) check constraint
DQL Commands:
12. Viewing data in the tables: - once data has been inserted into a
table, the next most logical operation would be to view what has been
inserted.
Syntax:
Select <col> to <col n> from tablename;
Select * from tablename;
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
13. Filtering table data: - while viewing data from a table, it is rare
that all the data from table will be required each time. Hence, sql must
give us a method of filtering out data that is not required data.
Syntax:
Select * from <tablename> order by <col1>,<col2> <[sortorder]>;
DCL commands:
Syntax:
GRANT <object privileges>
ON <objectname>
TO<username>
[WITH GRANT OPTION];
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Syntax:
REVOKE<object privilege>
ON
FROM<user name>;
WEEK-1
CREATING,ALTERING AND DROPPING TABLES AND INSERTING ROWS INTO A
TABLE (USE CONSTRAINTS WHILE CREATING TABLES) EXAMPLES USING
SELECT COMMAND .
EXAMPLE 1:
Table created.
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
METHOD 1:
SQL>Insert into
Student252(sid,sname,sbranch,dob,spercent) values(104,‘sri’,,’cse’,’27-
feb-05’,70);
1 row created.
METHOD 2:
SQL>Insert into
Student252 values(104,‘sri’,,’cse’,’27-feb-05’,70);
1 row created.
METHOD 3:
SQL>Insert into
Student252(sid,sname,sbranch,dob,spercent)
values(&sid, &sname,&sbranch,&dob,&spercent);
1 row created.
METHOD 4:
SQL>Insert into
Student252(sid,sname,sbranch,dob,spercent)
values(&sid, ‘&sname’,’&sbranch’,’&dob’,&spercent);
1 row created.
WEEK 2 (cont…1)
10
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
1) Creation, altering and dropping tables and inserting rows into a table
(use constraints while creating tables) examples using SELECT command.
Table altered.
Table altered.
DROPING A COLUMN
Table altered.
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
40 sanjeev 1500 13
10 rows selected.
10 rows updated.
10 rows selected.
Table renamed.
Example 3
12
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Table created.
Table dropped.
WEEK 3 (cont…1)
1) Creation, altering and dropping tables and inserting rows into a table
(use constraints while creating tables) examples using SELECT
command.
Example 1
13
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Table created.
1 row created.
SQL> /
Enter value for eid: 2
Enter value for ename: 'teja'
Enter value for age: 18
Enter value for esal: 20000
old 1: INSERT INTO emp252 VALUES (&eid, &ename, &age, &esal)
new 1: INSERT INTO emp252 VALUES (2, 'teja', 18, 20000)
1 row created.
SQL> /
Enter value for eid: 3
Enter value for ename: 'kiran'
Enter value for age: 19
Enter value for esal: 25000
old 1: INSERT INTO emp252 VALUES (&eid, &ename, &age, &esal)
14
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
1 row created.
SQL> /
Enter value for eid: 4
Enter value for ename: 'srinivas'
Enter value for age: 19
Enter value for esal: 30000
old 1: INSERT INTO emp252 VALUES (&eid, &ename, &age, &esal)
new 1: INSERT INTO emp252 VALUES (4, 'srinivas', 19, 30000)
1 row created.
SQL> /
Enter value for eid: 1
Enter value for ename: 'alan'
Enter value for age: 19
Enter value for esal: 29000
old 1: INSERT INTO emp252 VALUES (&eid, &ename, &age, &esal)
new 1: INSERT INTO emp252 VALUES (1, 'alan', 19, 29000)
INSERT INTO emp252 VALUES (1, 'alan', 19, 29000)
[SHOWING AN ERROR WHILE VIOLATING UNIQUE KEY
CONSTRAINT]
*
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.SYS_C003875) violated
SQL> /
Enter value for eid: 7
Enter value for ename: 'dravid'
Enter value for age: null
Enter value for esal: 100000
old 1: INSERT INTO emp252 VALUES (&eid, &ename, &age, &esal)
new 1: INSERT INTO emp252 VALUES (7, 'dravid', null, 100000)
INSERT INTO emp252 VALUES (7, 'dravid', null, 100000)
[SHOWING AN ERROR AS NOT NULL KEY CONSTRAINT IS
VIOLATED] *
ERROR at line 1:
15
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
SQL> /
Enter value for eid: 8
Enter value for ename: 'sachin'
Enter value for age: 35
Enter value for esal: 100
old 1: INSERT INTO emp252 VALUES (&eid, &ename, &age, &esal)
new 1: INSERT INTO emp252 VALUES (8, 'sachin', 35, 100)
INSERT INTO emp252 VALUES (8, 'sachin', 35, 100)
*
[NOT ALLOWING AS IT VOILATES CHECK CONSTRAINT FOR esal >
1000 VALUE]
ERROR at line 1:
ORA-02290: check constraint (SYSTEM.SYS_C003874) violated
Example 2
Table created.
16
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
1 row created.
SQL> /
Enter value for dno: 1
Enter value for dname: 'teja'
Enter value for dloc: 'sec'
old 1: INSERT INTO mdept252 VALUES (&dno, &dname, &dloc)
new 1: INSERT INTO mdept252 VALUES (1, 'teja', 'sec')
INSERT INTO mdept252 VALUES (1, 'teja', 'sec')
*
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.SYS_C003876) violated
SQL> /
Enter value for dno: null
Enter value for dname: 'sajithulhuq'
Enter value for dloc: 'kmm'
old 1: INSERT INTO mdept252 VALUES (&dno, &dname, &dloc)
new 1: INSERT INTO mdept252 VALUES (null, 'sajithulhuq', 'kmm')
INSERT INTO mdept252 VALUES (null, 'sajithulhuq', 'kmm')
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SYSTEM"."MDEPT230"."DNO")
Table altered.
17
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Example 3
Table created.
1 row created.
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
*
ERROR at line 1:
ORA-02292: integrity constraint (SYSTEM.SYS_C003877) violated - child
record
found
19
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Exercise
Table created.
1 row created.
SQL> /
Enter value for cnum: 2
Enter value for cname: 'teja'
Enter value for state: 'up'
Enter value for phno: 007
old 2: (&cnum, &cname, &state, &phno)
new 2: (2, 'teja', 'up', 007)
1 row created.
SQL> /
Enter value for cnum: 2
Enter value for cname: 'yama'
Enter value for state: 'ap'
Enter value for phno: 006
old 2: (&cnum, &cname, &state, &phno)
20
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
SQL> /
Enter value for cnum: 4
Enter value for cname: 'huu'
Enter value for state: 'ap'
Enter value for phno: 101
old 2: (&cnum, &cname, &state, &phno)
new 2: (4, 'huu', 'ap', 101)
1 row created.
Table created.
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
1 row created.
SQL> /
Enter value for ino: 1
Enter value for iname: 'pencil'
Enter value for iprice: 1.00
Enter value for qtyonhand: 3
old 1: INSERT INTO itm252 VALUES (&ino, &iname, &iprice, &qtyonhand)
new 1: INSERT INTO itm252 VALUES (1, 'pencil', 1.00, 3)
INSERT INTO itm252 VALUES (1, 'pencil', 1.00, 3)
*
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.ITM230_INO_PKKEY) violated
SQL> /
Enter value for ino: 2
Enter value for iname: 'powder'
Enter value for iprice: 3.00
Enter value for qtyonhand: 0
old 1: INSERT INTO itm252 VALUES (&ino, &iname, &iprice, &qtyonhand)
new 1: INSERT INTO itm252 VALUES (2, 'powder', 3.00, 0)
INSERT INTO itm252 VALUES (2, 'powder', 3.00, 0)
*
ERROR at line 1:
ORA-02290: check constraint (SYSTEM.ITM230_QTYOH_CHK) violated
22
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Table created.
Table created.
23
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
WEEK 4
2) Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT
EXISTS, UNIQUE, INTERSECT, Constraints.
Example: select the rollno and name of the student who secured 4th rank
in the class
TABLE DEFINITIONS
Table created.
1 row created.
CUST LAST FIRST ADDRESS1 ADDRESS2 CITY STATE PIN BIRTH STATUS
NO NAME NAME DATE
1001 UDUPI RAJ UPENDRABAU NEAR UDP KARNARATA 57610 12- A
G KALPANA P 1 DEC-62
1002 KUMAR RAJ A
1003 BAHADUR RAJ SHANTHI VILLA NEAR UDP KARNATAK 57610 1-AUG- V
MALLIKA A 1 70
1004 SIMON FELIX M-J-56 ALTOBETIM PJM GOA 40300 12-FEB- A
2 71
1005 KUTTY RAJAN A1 TRADERS NEAR RLY KNR KERALA 67001 9-JUN- A
STATION 71
1006 PAI SHILPA 12/4B POLICE MNG KARNATAK 57415 11- I
QUARTERS A 4 DEC-70
1007 JAIN RAKSHIT BOSCO R.K PLAZA BNG KARNATAK 57620 1-JAN- A
A 1 71
24
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
QUERIES
7) To select records where the pin code has not been entered.
SELECT *
FROM Customer
WHERE pin IS NULL;
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
13) To sort the customer data, state wise and within state by the last name.
SELECT state, first_name, last_name, pin
FROM Customer
ORDER BY state, last_name;
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
18) To retrieve rows where the state name begins with K and followed by any other
character.
SELECT first_name, last_name, state
FROM Customer
WHERE state LIKE ‘K%’;
19) To retrieve rows where the first name contains the word RAJ embedded in it.
SELECT first_name, last_name, state
FROM Customer
WHERE first_name LIKE ‘%RAJ%’;
20) To retrieve rows where the address2 contains the word UDUPI or UDIPI in which
the 3rd character may be anything.
SELECT first_name, last_name, state
FROM Customer
WHERE address2 LIKE ‘UD_PI’;
21) To retrieve rows where the cust_no has data representing any value between 1003
and 1005, both numbers included.
SELECT *
FROM Customer
WHERE cust_no BETWEEN 1003 AND 1005;
22) To retrieve rows of persons born after 9-JAN-70 and before 1-AUG-96.
SELECT *
FROM Customer
WHERE birth_date BETWEEN ’10-JAN-70’ AND ’31-JUL-96’;
23) To retrieve rows where the city has data which is equal to UDP or MNG or BNG or
PJM or MAR.
SELECT *
FROM Customer
WHERE city IN (‘UDP’, ‘MNG’, ‘BNG’, ‘PJM’, ‘MAR’);
TABLE DEFINITIONS
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Table created.
QUERIES
2) To sum the salary of each employee and sort it on the sum of basic.
SELECT emp_no, SUM(basic)
28
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
FROM salary
GROUP BY emp_no
ORDER BY SUM(basic);
3) To sum the salary of each employee and sort it in descending order on the sum of
basic.
SELECT emp_no, SUM(basic)
FROM salary
GROUP BY emp_no
ORDER BY SUM(basic) DESC;
4) To sum the salary of each employee and sort it in descending order on the sum of
basic. Display name also
SELECT s.emp_no, e.emp_name, SUM(s.basic)
FROM salary s, emp e
WHERE s.emp_no = e.emp_no
GROUP BY s.emp_no, e.emp_no
ORDER BY SUM(s.basic) DESC;
7) To group the data by average salary of each employee and display where average
basic is more than 2000..
SELECT s.emp_no, INITCAP(e.emp_name), AVG(s.basic)
FROM salary s, emp e
WHERE s.emp_no = e.emp_no
GROUP BY s.emp_no, e.emp_no
HAVING AVG(s.basic) >= 2000
ORDER BY AVG(s.basic);
SUBQUERIES
8) To list the employees who earn less than the average salary.
SELECT *
29
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
FROM salary
WHERE basic < (SELECT AVG(basic)
FROM salary);
WEEK 5
2) Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT
EXISTS, UNIQUE, INTERSECT, Constraints. Example: select the
rollno and name of the student who secured 4th rank in the class.
TABLE DEFINITIONS
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Table created.
Table created.
QUERIES
31
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
12) To sum the salary of each employee and sort it on the sum of basic.
SELECT emp_no, SUM(basic)
FROM salary
GROUP BY emp_no
ORDER BY SUM(basic);
13) To sum the salary of each employee and sort it in descending order on the sum of
basic.
SELECT emp_no, SUM(basic)
FROM salary
GROUP BY emp_no
ORDER BY SUM(basic) DESC;
14) To sum the salary of each employee and sort it in descending order on the sum of
basic. Display name also
SELECT s.emp_no, e.emp_name, SUM(s.basic)
FROM salary s, emp e
WHERE s.emp_no = e.emp_no
GROUP BY s.emp_no, e.emp_name
ORDER BY SUM(s.basic) DESC;
17) To group the data by average salary of each employee and display where average
basic is more than 2000..
SELECT s.emp_no, INITCAP(e.emp_name), AVG(s.basic)
FROM salary s, emp e
WHERE s.emp_no = e.emp_no
GROUP BY s.emp_no, e.emp_no
HAVING AVG(s.basic) >= 2000
ORDER BY AVG(s.basic);
SUBQUERIES
32
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
18) To list the employees who earn less than the average salary.
SELECT *
FROM salary
WHERE basic < (SELECT AVG(basic)
FROM salary);
WEEK 6
2) Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT
EXISTS, UNIQUE, INTERSECT, Constraints. Example: select the
rollno and name of the student who secured 4th rank in the class.
TABLE DEFINITIONS
33
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
BRANCH TABLE
CUSTOMER TABLE
LOAN TABLE
34
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
BORROWER TABLE
ACCOUNT TABLE
DEPOSITOR TABLE
35
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
QUERIES
SELECT branch_name
FROM Loan;
5) Find all loan numbers for loans made at the Perryridge branch with loan amounts
greater than Rs1200.
SELECT loan_number
FROM Loan
WHERE branch_name = ‘Perryridge’
AND amount > 1200;
6) Find all loan numbers for loans with loan amounts between Rs90,000 and Rs100,000.
SELECT loan_number
FROM Loan
WHERE amount BETWEEN 90000 AND 100000;
Or
SELECT loan_number
FROM Loan
WHERE amount <= 100000
AND amount >= 90000;
7) Find all loan numbers for loans with loan amounts not between Rs90,000 and
Rs100,000.
SELECT loan_number
36
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
FROM Loan
WHERE amount NOT BETWEEN 90000 AND 100000;
8) For all customers who have a loan from the bank, find their names, loan numbers and loan
amounts.
Or
9) Find the customer names, loan numbers and loan amounts for all loans at the Perryridge
branch.
Or
10) Find the names of all branches that have assets greater than atleast one branch located in
Brooklyn.
11) Find the names of all customers whose street address includes the substring ‘Main’.
SELECT customer_name
FROM Customer
WHERE customer_street LIKE ‘%Main%’;
12) To list in alphabetic order all customers who have a loan at the Perryridge branch.
37
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
SELECT *
FROM Loan
ORDER BY amount DESC, loan_number ASC;
14) To find all customers having a loan, an account or both at the bank, without duplicates.
(SELECT customer_name
FROM Depositor)
UNION
(SELECT customer_name
FROM Borrower);
15) To find all customers having a loan, an account or both at the bank, with duplicates.
(SELECT customer_name
FROM Depositor)
UNION ALL
(SELECT customer_name
FROM Borrower);
16) To find all customers having both a loan and an account at the bank, without duplicates.
(SELECT customer_name
FROM Depositor)
INTERSECT
(SELECT customer_name
FROM Borrower);
17) To find all customers having a loan, an account or both at the bank, with duplicates.
(SELECT customer_name
FROM Depositor)
INTERSECT ALL
(SELECT customer_name
38
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
FROM Borrower);
18) To find all customers who have an account but no loan at the bank, without duplicates.
19) To find all customers who have an account but no loan at the bank, with duplicates.
SELECT AVG(balance)
FROM Account
GROUP BY branch_name;
23) Find the number of depositors for each branch where average account balance is more
than Rs 1200.
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
GROUP BY branch_name
HAVING AVG(balance) > 1200;
SELECT AVG(balance)
FROM Account;
SELECT COUNT(*)
FROM Customer;
26) Find the average balance for each customer who lives in Harrision and has at least three
accounts.
27) Find all the loan number that appear in loan relation with null amount values.
SELECT loan_number
FROM Loan
WHERE amount IS NULL;
28) Find all customers who have both a loan and an account at the bank.
SELECT customer_name
FROM Borrower
WHERE customer_street IN (SELECT customer_name
FROM Depositor);
29) Find all customers who have both an account and a loan at the Perryridge branch
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
or
SELECT customer_name
FROM Borrower B
WHERE EXISTS (SELECT *
FROM Depositor D
WHERE D.customer_name = B.customer_name);
30) Find all customers who do not have a loan at the bank, but do not have an account the
bank.
31) Find the names of customers who do have a loan at the bank, and whose names are neither
Smith nor Jones.
32) Find the names of all branches that have assets greater than those of at least one branch
located in Brooklyn.
33) Find the names of all branches that have assets greater than that of each branch located in
Brooklyn.
SELECT branch_name
FROM Account
GROUP BY branch_name
HAVING AVG(balance) >= ALL (SELECT AVG(balance)
FROM Account
GROUP BY branch_name);
41
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
34) Find all customers who have an account at all the branches located in Brooklyn.
35) Find all customers who have at most one account at the Perryridge branch.
SELECT T.customer_name
FROM Depositor AS T
WHERE UNIQUE (SELECT R.customer_name
FROM Depositor AS R, Account AS A
WHERE T.customer_name = R.customer_name
AND R.account_number = A.account_number
AND A.branch_name = ‘Perryridge’);
36) Find all customers who have at least two accounts at the Perryridge branch.
37) Find the average account balance of those branches where the average account balance is
greater than 1200.
42
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
38) Find the maximum across all branches of the total balance at each branch.
SELECT MAX(tot_balance)
FROM (SELECT branch_name, SUM(balance)
FROM Account
GROUP BY branch_name)
AS Branch_total(branch_name, tot_balance);
39) Find the all customers who have an account but no loan at the bank.
SELECT d-CN
FROM (Depositor LEFT OUTER JOIN Borrower
ON Depositor.customer_name = Borrower.customer_name)
AS db1(d-CN, account_number, b-CN, loan_number)
WHERE b-CN is null;
40) Find the all customers who have either an account or a loan (but not both) at the bank.
SELECT customer_name
FROM (Depositor NATURAL FULL OUTER JOIN Borrower)
WHERE account_number IS NULL
OR loan_number IS NULL;
WEEK 7
5) Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT
EXISTS, UNIQUE, INTERSECT, Constraints. Example: select the
rollno and name of the student who secured 4th rank in the class.
43
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
GROUP FUNCTIONS:
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
STRING FUNCTIONS:
45
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
WEEK 8 (PL/SQL)
46
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Declare
<declaration stmts>
Begin
<executable stmts>
[exception <exceptional stmts>]----- optional
End;
/---end of buffer
Example: 1
Create a file DBFOR.SQL, to execute the FOR loop and display the variable.
At SQL Prompt type, ed dbfor to open notepad and type the below program:
Program
declare
cnt number;
begin
dbms_output.put_line('This is a demo of FOR loop ');
for cnt in 1..5 loop
dbms_output.put_line('loop number ' || cnt);
end loop;
end;
/
set serveroutput off
47
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
OUTPUT:-
This ia a demo of FOR loop
loop number 1
loop number 2
loop number 3
loop number 4
loop number 5
PS:
For syntax:
For <var> in <start_num> .. <endnum> loop
<statement(s);>
End loop;
Example: 2
Create a file DBREVFOR.SQL, to execute the REVERSE FOR loop and
display the variable.
Program
begin
dbms_ouput.put_line(‘This is a demo of REVERSE FOR loop’);
for cnt in reverse 1..10 loop
if mod(cnt, 2) = 0 then
dbms_output.put_line(‘loop counter ‘ || cnt);
end if;
end loop;
end;
/
OUTPUT:-
This is a demo of REVERSE FOR loop
loop counter 10
loop counter 8
48
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
loop counter 6
loop counter 4
loop counter 2
PS:
If <condition> then
<action(s);>
Else
<action(s);>
End if;
If <condition> then
<action(s);>
Elsif <condition> then
<action(s);>
else
<action(s);>
End if;
Example: 3
Create a file DBLOOP.SQL, to execute the LOOP loop and display the
variable.
Program
set serveroutput on
declare
cnt number(2) := 0;
begin
dbms_ouput.put_line(‘This is a demo of LOOP loop’);
loop
cnt := cnt + 1;
exit when cnt > 10;
dbms_output.put_line(‘loop counter ‘ || cnt);
end loop;
49
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
end;
/
set serveroutput off
OUTPUT:-
This is the demo of LOOP loop
loop counter 1
loop counter 2
loop counter 3
loop counter 4
loop counter 5
loop counter 6
loop counter 7
loop counter 8
loop counter 9
loop counter 10
PS:
Loop syntax:
loop
<statement(s);>
Exit when <condition>;
End loop;
Example: 4
Create a file DBWHILE.SQL, to execute the WHILE loop and display the
variable.
Program
set serveroutput on
declare
cnt number(2) := 1;
begin
dbms_ouput.put_line(‘This is a demo of WHILE loop’);
50
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
OUTPUT:-
This is a demo of WHILE loop
loop counter : 1
loop counter : 2
loop counter : 3
loop counter : 4
loop counter : 5
loop counter : 6
loop counter : 7
loop counter : 8
loop counter : 9
loop counter : 10
PS:
while syntax:
while <condition> loop
<statement(s);>
End loop;
Example: 4
Write a program EMPDATA.SQL, to retrieve the employee details of an
employee whose number is input by the user .
Program
-- PROGRAM TO RETRIEVE EMP DETAILS
set serveroutput on
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
dbasic emp.emp_basic%type;
ddesig emp.desig%type;
begin
select emp_name, basic, design
into dname, dbasic, ddesig
from emp
where emp_no = &n;
dbms_ouput.put_line(‘Employee Details:);
dbms_output.put_line(‘Name: ‘ || dname);
dbms_output.put_line(‘Basic: ‘ || dbasic);
dbms_output.put_line(‘Designation: ‘ || ddesig);
end;
/
OUTPUT:-
enter employee number:
13
old 9:where eno =&n;
employee details
Name:allen
basic:9500
desig:mech
PS:
Similarly you can use other SQL statements in the PL/SQL block
Exercises:
52
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
ANSWER:-
declare
n number(20):=123;
s number(13):=0;
d number(3):=1;
r number(3):=10;
begin
d:=mod(n,10);
s:=(s*r)+d;
n:=n/r;
end loop;
end;
OUTPUT:-
53
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
ANSWER:-
accept number n
declare
isum number(2):=0;
i number;
n number:=&n;
begin
isum:=isum+i;
end loop;
end;
OUTPUT:-
sum is 28
54
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
ANSWER:-
set serveroutput on
declare
area number(5);
rad number(3);
pi number(4):=3.14;
begin
area:=pi*rad*rad;
end loop;
end;
OUTPUT:-
55
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
area is :27
area is :48
area is :75
area is :108
area is :147
WEEK 9 (PL/SQL)
56
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Example: 1
Create a file (NEWINS.SQL), to insert into a new table, NEWEMP, the
record of any employee whose number is input by the user.
Program
prompt Enter Employee Number:
accept userno number
declare
dno number(4);
dname varchar2(30);
ddate date;
dbasic number(10);
begin
select emp_no, emp_name, join_date, basic
into dno, dname, ddate, dbasic
from emp
where emp_no = &userno;
if sql%rowcount > 0
then
57
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Example: 2
Create a file (NEWINS2.SQL), to insert into a new table, NEWEMP, the
record of any employee whose number is input by the user. Also display on
the screen the employee details and to handle errors like user entering a
number which does not exist in the table.
Program
prompt Enter Employee Number:
accept userno number
declare
dno number(4);
dname varchar2(30);
ddate date;
dbasic number(10);
begin
select emp_no, emp_name, join_date, basic
into dno, dname, ddate, dbasic
from emp
where emp_no = &userno;
if sql%rowcount > 0
then
insert into newemp
values (dno, dname, ddate, dbasic);
exception
when no_data_found then
dbms_output.put_line (‘Record ‘ || &userno || ‘ does not exist’);
58
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
end;
/
Example: 3
Create a file (CALCTAX.SQL), to calculate tax for a specific employee and
display name and tax.
Program
prompt Enter Employee Number:
accept userno number
declare
tot_basic number(10, 2);
tax number(10, 2);
name varchar2(30);
begin
select emp_name, basic
into name, tot_basic
from emp
where emp_no = &userno;
exception
when no_data_found then
dbms_output.put_line (‘Record ‘ || &userno || ‘ does not exist’);
end;
/
PS:
EXECPTIONS
59
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
User defined exceptions must be declared in the declare section with the
reserved word, EXCEPTION.
60
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Exercises:
1) Write a PL/SQL code block that will accept an account number from
the user and debit an amount of RS2000 from the account. If the
account has a minimum balance of 500 after amount is debited the
process should set a freeze on the account by setting the status to F.
(use table schema Accounts (acno, balance, status)
2) Write a PL/SQL block of code to achieve the following:
If the price of the product is >4000 then change the price to 4000. The
price change is to be recorded in the old price table along with product
number and date on which the price was last changed.
(use table schemas Product(pno, price) and Old_Price(pno,
date_of_change, oldprice)
WEEK 10 (PL/SQL)
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Example: 1
Create a PL/SQL program using cursors, to retrieve first tuple from the
department relation.
(use table dept(dno, dname, loc))
Program
declare
vdno dept.deptno%type;
vdname dept.dname%type;
vloc dept.loc%type;
cursor c1 is select * from dept;
or // cursor c1 is select * from dept where rowno = 1;
begin
open c1;
fetch c1
into vdno,vdname,vloc;
62
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
PS:
Cursors are used when the SQL select statement is expected to return more than
1 row.
A cursor must be declared and its definition contains a query and is defined in
the DECLARE section of the program.
A cursor must be opened before processing and closed after processing.
(Similar to how files are opened and closed in a C program).
Example: 2
Create a PL/SQL program using cursors, to retrieve each tuple from the
department relation.
(use table dept(dno, dname, loc))
Program
declare
vdept dept%rowtype;
cursor c1 is select * from dept;
begin
63
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
end;
/
PS:
The cursor for loop can be used to process multiple records. The advantage of
cursor for loop is that the loop itself will open the cursor, read the records into
the cursor from the table until end of file and close the cursor.
Example: 3
Create a PL/SQL program using cursors, to display the number, name, salary
of the three highest paid employees.
(use table emp(empno, ename,sal))
Program
declare
no emp.empno%type;
name emp.ename%type;
salary emp.sal%type;
cursor c1 is select empno, ename, sal from emp order by sal desc;
begin
open c1;
64
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
loop
fetch c1 into no,name,salary;
exit when c1 %notfound;
exit when c1 %rowcount >3;
dbms_output.put_line(no||name||salary);
end loop;
close c1;
end;
/
PS:
Cursors Attributes:
There are 4 cursor attributes used to provide information on the status of a
cursor.
%NOTFOUND – To determine if a row was retrieved
Used after FETCH
NOTFOUND is TRUE if row is not retrieved
NOTFOUND is FALSE if row is retrieved
%FOUND – To determine if a row was retrieved.
Used after FETCH
FOUND is TRUE if row is retrieved
FOUND is FALSE if row is not retrieved
%ROWCOUNT – To determine the number of rows retrieved
ROWCOUNT is 0 when cursor is opened
ROWCOUNT returns the number of rows retrieved
%ISOPEN – To determine the cursor is open
ISOPEN is TRUE if a cursor is open
ISOPEN is FALSE if a cursor is not open
Example: 4
Create a PL/SQL program using cursors, to delete the employees whose
salary is more than 3000.
Program
declare
vrec emp%rowtype;
cursor c1 is select * from emp where sal>3000 for update;
begin
open c1;
65
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
loop
fetch c1 into vrec;
exit when c1 %notfound;
delete from emp where current of c1;
dbms_output.put_line('Record deleted');
end loop;
close c1;
end;
/
PS:
In order to DELETE or UPDATE rows, the cursor must be defined with the
FOR UPDATE clause.
Example: 5
Create a PL/SQL program using cursors, to update the salary of each
employee by the avg salary if their salary is less than avg salary.
Program
declare
vrec emp%rowtype;
avgsal number(10,2);
cursor c1 is select * from emp for update;
begin
select avg(sal) into avgsal from emp;
for vrec in c1 loop
if vrec.sal < avgsal then
vrec.sal := avgsal;
update emp set sal = vrec.sal where current of c1;
dbms_output.put_line('Record updated');
end if;
end loop;
end;
/
PS:
Variable Attributes:
66
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Example: 6
Create a PL/SQL program using cursors, to insert into a table, NEWEMP, the
record of ALL MANAGERS. Also DISPLAY on the screen the NO, NAME,
JOIN_DATE. Handle any user defined exceptions.
(use table emp(emp_no, emp_name, join_date, desig))
Program
set serveroutput on
declare
ctr number(2) := 2;
dno number(4);
dname varchar2(30);
ddate date;
cursor cur_mgr is
select emp_no, emp_name, join_date
from emp
where upper(desig) = ‘MGR’;
no_manager_found exception;
begin
open cur_mgr;
loop
fetch cur_mgr
into dno, dname, ddate;
67
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
end loop;
if cur_mgr%rowcount = 0
then
close cur_mgr;
raise no_manager_found;
end if;
exception
when no_manager_found then
dbms_output.put_line(‘NO RECORS FOUND’);
end;
/
Exercises:
1) Create a PL/SQL program using cursors, to insert into a table,
NEWEMP, for any designation input by the user from the keyboard.
Handle any user defined exceptions.
68
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
WEEK 11 (PL/SQL)
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Program
CREATE OR REPLACE PROCEDURE TOTSALES
(CID IN CSTMAST.CSTID%TYPE, SAL OUT NUMBER)
IS
id TRN.ITMID%TYPE;
qty TRN.TRNQTY%TYPE;
price ITMMAST.ITMPRICE%TYPE;
sales NUMBER(10, 2) := 0;
cursor cur_tr is
select trn.itmid, trnqty, itmprice
from trn, itmmast
where trn.cstid = cid
and trn.itmid = itmmast.itmid;
begin
open cur_tr;
loop
fetch cur_tr into id, qty, price;
if cur_tr%rowcount = 0
then
raise_application_error(-20020, ‘ERREOR!!!THERE IS NO
DATA’);
end if;
exit when cur_tr%notfound;
sales := sales + qty * price;
end loop;
close cur_tr;
sal := sales;
end;
/
70
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
PS:
Procedural Objects
Groups of SQL and PL/SQL statements can be stored in the database. The code
stored once in the database can be used by multiple applications. Since the code
is in the database, which is in the server, processing is faster.
Procedures and functions are also referred to as sub-programs as they can take
parameters and be invoked.
Procedures:
Procedures are sub-programs, which will perform an action and functions are
subprograms that are generally coded to compute some value.
The clients execute the procedure or function and the processing is done in the
server.
Procedures can receive and return values from and to the caller.
Communication is passed to a procedure through a parameter and
communication is passed out of a procedure through a parameter.
When calling a procedure, the parameters passed can be declared to be IN, OUT
or IN OUT.
The IN parameter is used to pass values to the procedure being called. It
behaves like a constant inside the procedure, i.e., cannot be assigned values
inside the procedure.
The OUT parameter is used to pass values out of a procedure to the caller of the
procedure. It behaves like a uninitialized variable inside the procedure.
71
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Inclusion Dependency:
An Inclusion Dependency is a statement of the form that some columns of a
relation are contained in other columns. A foreign key constraint is an example
of inclusion dependency.
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
management.
69. What are the primitive operations common to all record management
systems?
Addition, deletion and modification.
70. Name the buffer in which all the commands that are typed in are stored
‘Edit’ Buffer
72. Are the resulting relations of PRODUCT and JOIN operation the
73
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
same?
No.
PRODUCT: Concatenation of every row in one relation with every row in
another.
JOIN: Concatenation of rows from one relation and related rows from another.
75. Which part of the RDBMS takes care of the data dictionary? How
Data dictionary is a set of tables and database objects that is stored in a special
area of the database and maintained exclusively by the kernel.
78. Define SQL and state the differences between SQL and other
conventional programming Languages
74
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
79. Name the three major set of files on disk that compose a database in
Oracle
There are three major sets of files on disk that compose a database. All the files
are binary. These are
Ø Database files
Ø Control files
Ø Redo logs
The most important of these are the database files where the actual data resides.
The control files and the redo logs support the functioning of the architecture
itself.
All three sets of files must be present, open, and available to Oracle for any data
on the database to be useable. Without these files, you cannot access the
database, and the database administrator might have to recover some or all of
the database using a backup, if there is one.
81. What are the four Oracle system processes that must always be up and
running for the database to be useable
The four Oracle system processes that must always be up and running for the
database to be useable include DBWR (Database Writer), LGWR (Log Writer),
SMON (System Monitor), and PMON (Process Monitor).
82. What are database files, control files and log files. How many of these
files should a database have at least? Why?
75
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
Database Files
The database files hold the actual data and are typically the largest in size.
Depending on their sizes, the tables (and other objects) for all the user accounts
can go in one database file—but that's not an ideal situation because it does not
make the database structure very flexible for controlling access to storage for
different users, putting the database on different disk drives, or backing up and
restoring just part of the database.
You must have at least one database file but usually, more than one files are
used. In terms of accessing and using the data in the tables and other objects,
the number (or location) of the files is immaterial.
The database files are fixed in size and never grow bigger than the size at which
they were created Control Files
The control files and redo logs support the rest of the architecture. Any database
must have at least one control file, although you typically have more than one to
guard against loss. The control file records the name of the database, the date
and time it was created, the location of the database and redo logs, and the
synchronization information to ensure that all three sets of files are always in
step. Every time you add a new database or redo log file to the database, the
information is recorded in the control files.
Redo Logs
Any database must have at least two redo logs. These are the journals for the
database; the redo logs record all changes to the user objects or system objects.
If any type of failure occurs, the changes recorded in the redo logs can be used
to bring the database to a consistent state without losing any committed
transactions. In the case of non-data loss failure, Oracle can apply the
information in the redo logs automatically without intervention from the DBA.
The redo log files are fixed in size and never grow dynamically from the size at
which they were created.
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
86. Name two utilities that Oracle provides, which are use for backup and
recovery.
Along with the RDBMS software, Oracle provides two utilities that you can use
to back up and restore the database. These utilities are Export and Import.
The Export utility dumps the definitions and data for the specified part of the
database to an operating system binary file. The Import utility reads the file
produced by an export, recreates the definitions of objects, and inserts the data
If Export and Import are used as a means of backing up and recovering the
database, all the changes made to the database cannot be recovered since the
export was performed. The best you can do is recover the database to the time
77
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
87. What are stored-procedures? And what are the advantages of using
them.
Stored procedures are database objects that perform a user defined operation. A
stored procedure can have a set of compound SQL statements. A stored
procedure executes the SQL commands and returns the result to the client.
Stored procedures are used to reduce network traffic.
88. How are exceptions handled in PL/SQL? Give some of the internal
exceptions' name
PL/SQL exception handling is a mechanism for dealing with run-time errors
encountered during procedure execution. Use of this mechanism enables
execution to continue if the error is not severe enough to cause procedure
termination.
The exception handler must be defined within a subprogram specification.
Errors cause the program to raise an exception with a transfer of control to the
exception-handler block. After the exception handler executes, control returns
to the block in which the handler was defined. If there are no more executable
statements in the block, control returns to the caller.
User-Defined Exceptions
PL/SQL enables the user to define exception handlers in the declarations area of
subprogram specifications. User accomplishes this by naming an exception as
in the following example:
ot_failure EXCEPTION;
In this case, the exception name is ot_failure. Code associated with this handler
is written in the EXCEPTION specification area as follows:
EXCEPTION
when OT_FAILURE then
out_status_code := g_out_status_code;
out_msg := g_out_msg;
The following is an example of a subprogram exception:
EXCEPTION
when NO_DATA_FOUND then
g_out_status_code := 'FAIL';
RAISE ot_failure;
Within this exception is the RAISE statement that transfers control back to the
ot_failure exception handler. This technique of raising the exception is used to
invoke all user-defined exceptions.
78
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
System-Defined Exceptions
Exceptions internal to PL/SQL are raised automatically upon error.
NO_DATA_FOUND is a system-defined exception. Table below gives a
complete list of internal exceptions.
79
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
(a) i & iii because theta joins are joins made on keys that are not primary keys.
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
(d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in
UNIONS
81
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
103. What is cold backup and hot backup (in case of Oracle)?
Ø Cold Backup:
It is copying the three sets of files (database files, redo logs, and control file)
when the instance is shut down. This is a straight file copy, usually from the
disk directly to tape. You must shut down the instance to guarantee a consistent
copy.
If a cold backup is performed, the only option available in the event of data file
loss is restoring all the files from the latest backup. All work performed on the
database since the last backup is lost.
Ø Hot Backup:
Some sites (such as worldwide airline reservations systems) cannot shut down
the database while making a backup copy of the files. The cold backup is not an
available option.
So different means of backing up database must be used — the hot backup.
Issue a SQL command to indicate to Oracle, on a tablespace-by-tablespace
basis, that the files of the tablespace are to backed up. The users can continue to
make full use of the files, including making changes to the data. Once the user
has indicated that he/she wants to back up the tablespace files, he/she can use
the operating system to copy those files to the desired backup destination.
The database must be running in ARCHIVELOG mode for the hot backup
option.
If a data loss failure does occur, the lost database files can be restored using the
hot backup and the online and offline redo logs created since the backup was
82
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
done. The database is restored to the most consistent state without any loss of
committed transactions.
104. What are Armstrong rules? How do we say that they are complete
and/or sound
The well-known inference rules for FDs
Ø Reflexive rule :
If Y is subset or equal to X then X Y.
Ø Augmentation rule:
If X Y then XZ YZ.
Ø Transitive rule:
If {X Y, Y Z} then X Z.
Ø Decomposition rule :
If X YZ then X Y.
Ø Union or Additive rule:
If {X Y, X Z} then X YZ.
Ø Pseudo Transitive rule :
If {X Y, WY Z} then WX Z.
Of these the first three are known as Amstrong Rules. They are sound because it
is enough if a set of FDs satisfy these three. They are called complete because
using these three rules we can generate the rest all inference rules.
105. How can you find the minimal key of relational schema?
Minimal key is one which can identify each tuple of the given relation schema
uniquely. For finding the minimal key it is required to find the closure that is
the set of all attributes that are dependent on any given set of attributes under
the given set of functional dependency.
Algo. I Determining X+, closure for X, given set of FDs F
1. Set X+ = X
2. Set Old X+ = X+
3. For each FD Y Z in F and if Y belongs to X+ then add Z to X+
4. Repeat steps 2 and 3 until Old X+ = X+
83
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
84
WWW.CSEROCKZ.COM
DataBaseManagementSystems LAB MANUAL
EMAIL: [email protected]
www.cserockz.com
Keep Watching for Regular Updates….!!
85
WWW.CSEROCKZ.COM