Dbms Complete Lab Manual
Dbms Complete Lab Manual
LAB MANUAL
A Helpful Hand
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DDL commands:
1. The Create Table Command: - it defines each column of the table
uniquely. Each column has minimum of three attributes, a name , data
type and size.
Syntax:
Create table <table name> (<col1> <datatype>(<size>),<col2>
<datatype><size>));
Ex:
create table emp(empno number(4) primary key, ename char(10));
2. Modifying the structure of tables.
a)add new columns
Syntax:
Alter table <tablename> add(<new col><datatype(size),<new
col>datatype(size));
Ex:
alter table emp add(sal number(7,2));
3. Dropping a column from a table.
Syntax:
Alter table <tablename> drop column <col>;
Ex:
alter table emp drop column sal;
4. Modifying existing columns.
Syntax:
Alter table <tablename> modify(<col><newdatatype>(<newsize>));
Ex:
alter table emp modify(ename varchar2(15));
3
DataBaseManagementSystems
LAB MANUAL
DML commands:
8. Inserting Data into Tables: - once a table is created the most
natural thing to do is load this table with data to be manipulated later.
Syntax 1:
insert into <tablename> (<col1>,<col2>..<col n>) values(<val 1>,
<val 2>.<val n>);
Syntax 2:
4
DataBaseManagementSystems
LAB MANUAL
Syntax 3:
insert into <tablename> values(<val 1>,<val 2>.,<val n>);
Ex 1:
Insert into skc (sname,rollno,class,dob,fee_paid)
values(sri,104B,cse,27-feb-05,10000.00);
Ex 2:
insert into skc values(&sname,&roll no,&class);
enter sname:sri
enter roll no:104B
enter class:cse
1 row created.
Ex 3:
insert into skc values(sri,104B,cse,27-feb-05,10000.00);
9. Delete operations.
a) remove all rows
Syntax:
delete from <tablename>;
b) removal of a specified row/s
Syntax:
delete from <tablename> where <condition>;
10. Updating the contents of a table.
a) updating all rows
5
DataBaseManagementSystems
LAB MANUAL
Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp>;
DataBaseManagementSystems
LAB MANUAL
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.
a) all rows and all columns
Syntax:
Select <col> to <col n> from tablename;
Select * from tablename;
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
7
DataBaseManagementSystems
LAB MANUAL
DCL commands:
Oracle provides extensive feature in order to safeguard information
stored in its tables from unauthoraised viewing and damage.The rights
that allow the user of some or all oracle resources on the server are
called privileges.
a) Grant privileges using the GRANT statement
The grant statement provides various types of access to database
objects such as tables,views and sequences and so on.
Syntax:
GRANT <object privileges>
ON <objectname>
TO<username>
[WITH GRANT OPTION];
b) Reoke permissions using the REVOKE statement:
The REVOKE statement is used to deny the Grant given on an object.
Syntax:
REVOKE<object privilege>
ON
8
DataBaseManagementSystems
LAB MANUAL
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:
CREATING A STUDENT RELATION TABLE WITH ALL DATATYPES:
DataBaseManagementSystems
LAB MANUAL
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.
QUERY THE TABLE VALUES:
ALL ROWS AND ALL COLUMNS:
SNAME
SBRANCH DOB
SPERCENT
--------------- --------------------- --------------- -------------------ravi
it
30-1-95
60
teja
cse 21-07-87
55
kiran
mech
12-05-92
60
sri
cse 30-07-90
70
sajith
eee 12-06-89
55
ram
ece 07-07-85
40
WEEK 2 (cont1)
1) Creation, altering and dropping tables and inserting rows into a table
(use constraints while creating tables) examples using SELECT command.
MODIFYING THE STRUCTURE OF TABLE
ADDING A NEW COLUMN
10
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
SET age=18;
10 rows updated.
QUERY THE TABLE VALUES
SQL> SELECT *
FROM Emp252;
ENO ENAME
ESAL DEPTNO AGE
----- -------------------- ---------- ---------- ---------30 ravi
51000
3
18
31 teja
31000
2
18
29 kiran
31200
1
18
45 allen
41000
3
18
33 sajith
51000
4
18
46 geetha
11000
4
18
90 veena
16000
3
18
85 pragna
61000
1
18
84 harsha
91000
3
18
40 sanjeev
1500
13
18
10 rows selected.
RENAMING THE TABLE:
SQL> RENAME Emp252
TO Emp1252;
Table renamed.
SELECTING THE TABLE VALUES
SQL> SELECT *
FROM Emp1252;
Example 3
DataBaseManagementSystems
LAB MANUAL
dloc VARCHAR(25));
Table created.
WEEK 3 (cont1)
1) Creation, altering and dropping tables and inserting rows into a table
(use constraints while creating tables) examples using SELECT
command.
CREATING A TABLE WITH KEY CONSTRAINTS
Example 1
CREATING A TABLE WITH UNIQUE , NOT NULL, CHECK AND
DEFAULT CONSTRAINT:
SQL> CREATE TABLE emp252
(eid NUMBER(5) UNIQUE,
ename VARCHAR(10) DEFAULT(UNKNOWN),
age NUMBER(3) NOT NULL,
esal NUMBER(7) CHECK(esal > 1000));
13
DataBaseManagementSystems
LAB MANUAL
Table created.
INSERTING RECORDS INTO TABLE:
SQL> INSERT INTO emp252 VALUES (&eid, &ename, &age, &esal);
Enter value for eid: 1
Enter value for ename: 'ravi'
Enter value for age: 18
Enter value for esal: 10000
old 1: INSERT INTO emp252 VALUES (&eid, &ename, &age, &esal)
new 1: INSERT INTO emp252 VALUES (1, 'ravi', 18, 10000)
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)
new 1: INSERT INTO emp252 VALUES (3, 'kiran', 19, 25000)
1 row created.
SQL> /
Enter value for eid: 4
Enter value for ename: 'srinivas'
Enter value for age: 19
Enter value for esal: 30000
14
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
Example 2
CREATING A TABLE WITH PRIMARY KEY CONSTRAINT:
SQL> CREATE TABLE mdept252
(dno NUMBER(5),
dname CHAR(10),
dloc VARCHAR(10),
PRIMARY KEY (dno));
Table created.
SQL> desc mdept252;
Name
Null? Type
----------------------------------------- -------- ---------------------------DNO
NOT NULL NUMBER(5)
DNAME
CHAR(10)
DLOC
VARCHAR2(10)
INSERTING RECORDS INTO MASTER DEPARTMENT TABLE:
SQL> INSERT INTO mdept252 VALUES (&dno, &dname, &dloc);
Enter value for dno: 1
Enter value for dname: 'ravi'
Enter value for dloc: 'hyd'
old 1: INSERT INTO mdept252 VALUES (&dno, &dname, &dloc)
new 1: INSERT INTO mdept252 VALUES (1, 'ravi', 'hyd')
16
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")
ADDING A PRIMARY KEY TO AN EXISTING TABLE:
SQL> ALTER TABLE student252 ADD PRIMARY KEY (sid);
Table altered.
SQL> ALTER TABLE emp252 ADD PRIMARY KEY (eid);
ALTER TABLE emp252 ADD PRIMARY KEY (eid)
*
[ GIVING AN ERROR AS ONE TABLE CAN HAVE A SINGLE PRIMARY
KEY AT COLUMN LAVEL]
ERROR at line 1:
ORA-02261: such unique or primary key already exists in the table
17
DataBaseManagementSystems
LAB MANUAL
Example 3
CREATING A TABLE WITH FORIEGN KEY CONSTRAINT:
SQL> CREATE TABLE detailemp252
(eid NUMBER(5) REFERENCES mdept230 (dno),
ename VARCHAR(10),
esal NUMBER(7));
Table created.
ESAL
18
DataBaseManagementSystems
LAB MANUAL
19
DataBaseManagementSystems
LAB MANUAL
Exercise
CREATING A CUSTOMER TABLE USING CONSTRAINTS :
SQL> CREATE TABLE cust252
(cnum NUMBER(5),
cname VARCHAR(10),
state VARCHAR(10) DEFAULT ('ap'),
phno NUMBER(5),
CONSTRAINT cnum_pkkey PRIMARY KEY (cnum));
Table created.
SQL> INSERT INTO cust252 VALUES (&cnum, &cname, &state, &phno);
Enter value for cnum: 1
Enter value for cname: 'ravi'
Enter value for state: 'bihar'
Enter value for phno: 001
old 2: (&cnum, &cname, &state, &phno)
new 2: (1, 'ravi', 'bihar', 001)
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
DataBaseManagementSystems
LAB MANUAL
PHNO
DataBaseManagementSystems
LAB MANUAL
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
DataBaseManagementSystems
LAB MANUAL
23
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
SQL> CREATE TABLE Customer (
cust_no
NUMBER(4)
PRIMARY KEY,
last_name
VARCHAR2(20),
first_name
VARCJHAR2(20)
NOT NULL,
address1
VARCHAR2(20),
address2
VARCHAR2(20),
city
VARCHAR2(3),
state
VARCHAR2(20),
pin
VARCHAR2(6),
birth_date
DATE,
status
VARCHAR2(1),
CHECH (status IN (V, I, A))
);
Table created.
Insert the following data:
1 row created.
CUST
NO
1001
LAST
NAME
UDUPI
FIRST
NAME
RAJ
ADDRESS1
ADDRESS2
CITY
STATE
PIN
UPENDRABAU
G
NEAR
KALPANA
UDP
P
KARNARATA
57610
1
1002
1003
KUMAR
BAHADUR
RAJ
RAJ
SHANTHI VILLA
UDP
KARNATAKA
SIMON
FELIX
M-J-56
NEAR
MALLIKA
ALTOBETIM
PJM
GOA
1005
KUTTY
RAJAN
A1 TRADERS
KNR
KERALA
1006
PAI
SHILPA
12/4B
MNG
KARNATAKA
1007
JAIN
RAKSHIT
BOSCO
NEAR RLY
STATION
POLICE
QUARTERS
R.K PLAZA
57610
1
40300
2
67001
1004
BNG
KARNATAKA
57415
4
57620
1
BIRTH
DATE
12DEC-62
1-AUG70
12-FEB71
9-JUN71
11DEC-70
1-JAN71
STATUS
A
A
V
A
A
I
A
24
DataBaseManagementSystems
LAB MANUAL
QUERIES
1) To list all the fields from the table Customer.
SEELCT *
FROM Customer;
2) To list the first name, last name.
SELECT first_name, last_name
FROM Customer;
3) To list the first name and last name of persons in Karnataka.
SELECT first_name, last_name
FROM Customer
WHERE state = KARNATAKA;
4) To list all the columns for invalid persons.
SELECT *
FROM Customer
WHERE status = I;
5) To list the names of active customers.
SELECT first_name, last_name
FROM Customer
WHERE status = A;
6) To list the name and address using concatenation.
SELECT first_name || || last_name, address1 || , || address2 || , || city || ,
|| state || - || pin
FROM Customer;
7) To select records where the pin code has not been entered.
SELECT *
FROM Customer
WHERE pin IS NULL;
8) To select the single occurrence of any value from the table.
SELECT DISTINCT state
FROM Customer;
9) To select rows of valid customers from Karnataka.
SELECT *
FROM Customer
WHERE state = KARNATAKA
AND status = V;
25
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
TABLE DEFINITIONS
SQL> CREATE TABLE Emp (
emp_no
NUMBER,
emp_name
VARCHAR(20),
join_date
DATE,
join_basic
NUMBER(7, 2),
27
DataBaseManagementSystems
LAB MANUAL
EMP NAME
Subhas bose
Nadeem shah
Charles
babbage
Shreyas kumar
George boole
JOIN DATE
01-JUN-96
01-JUN-96
01-JUN-96
JOIN BASIC
3000
2500
3000
01-JUL-96
01-JUL-96
2500
2800
BASIC
COMMISSION
DEDUCTION
1001
1002
1003
1004
1005
1001
1002
1003
1004
1005
3000
2500
3000
2500
2800
3000
2500
3000
2500
2800
200
120
500
200
100
200
120
500
200
100
250
200
290
300
250
250
200
290
300
150
SALARY
DATE
30-JUN-96
30-JUN-96
30-JUN-96
30-JUN-96
30-JUN-96
31-JUL-96
31-JUL-96
31-JUL-96
31-JUL-96
31-JUL-96
QUERIES
1) To sum the salary of each employee.
SELECT emp_no, SUM(basic)
FROM salary
GROUP BY emp_no;
2) To sum the salary of each employee and sort it on the sum of basic.
SELECT emp_no, SUM(basic)
FROM salary
28
DataBaseManagementSystems
LAB MANUAL
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;
5) To group the data by average salary of each employee.
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
ORDER BY AVG(s.basic);
6) To group the basic by month.
SELECT TO_CHAR(salary_date, MONTH) MONTH, SUM(basic)
TOTAL BASIC
FROM salary
GROUP BY TO_CHAR(salary_date, MONTH);
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 *
FROM salary
29
DataBaseManagementSystems
LAB MANUAL
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.
3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and
MIN), GROUP BY, HAVING and Creation and Dropping of Views.
4) Queries using Conversions, functions (to_char, to_num, and to_date),
string function (Conactenation, lpad, rpad, ltrim, rtrim, lower, upper,
initcap, length, substr, and instr), date functions (sysdate, next_day,
add_months, last_day, months_between, least, greatest, trunk, round,
to_char, to_date).
TABLE DEFINITIONS
SQL> CREATE TABLE Emp (
emp_no
NUMBER,
emp_name
VARCHAR(20),
join_date
DATE,
join_basic
NUMBER(7, 2),
PRIMARY KEY (emp_no)
30
DataBaseManagementSystems
LAB MANUAL
);
Table created.
Insert the following data:
EMP NO
1001
1002
1003
1004
1005
EMP NAME
Subhas bose
Nadeem shah
Charles
babbage
Shreyas kumar
George boole
JOIN DATE
01-JUN-96
01-JUN-96
01-JUN-96
JOIN BASIC
3000
2500
3000
01-JUL-96
01-JUL-96
2500
2800
BASIC
COMMISSION
DEDUCTION
1001
1002
1003
1004
1005
1001
1002
1003
1004
1005
3000
2500
3000
2500
2800
3000
2500
3000
2500
2800
200
120
500
200
100
200
120
500
200
100
250
200
290
300
250
250
200
290
300
150
SALARY
DATE
30-JUN-96
30-JUN-96
30-JUN-96
30-JUN-96
30-JUN-96
31-JUL-96
31-JUL-96
31-JUL-96
31-JUL-96
31-JUL-96
QUERIES
11) To sum the salary of each employee.
SELECT emp_no, SUM(basic)
FROM salary
GROUP BY emp_no;
12) To sum the salary of each employee and sort it on the sum of basic.
SELECT emp_no, SUM(basic)
FROM salary
31
DataBaseManagementSystems
LAB MANUAL
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;
15) To group the data by average salary of each employee.
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
ORDER BY AVG(s.basic);
16) To group the basic by month.
SELECT TO_CHAR(salary_date, MONTH) MONTH, SUM(basic)
TOTAL BASIC
FROM salary
GROUP BY TO_CHAR(salary_date, MONTH);
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
18) To list the employees who earn less than the average salary.
SELECT *
32
DataBaseManagementSystems
LAB MANUAL
FROM salary
WHERE basic < (SELECT AVG(basic)
FROM salary);
19) To list the employees whose deduction is 150.
SELECT *
FROM salary
WHERE emp_no IN (SELECT emp_no
FROM salary
WHERE deduction = 150);
20) To list the names of employees and salary details, whose basic is less than the average
salary.
SELECT s.*, e.emp_name
FROM salary s, emp e
WHERE s.emp_no = e.emp_no
AND s.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.
3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and
MIN), GROUP BY, HAVING and Creation and Dropping of Views.
4) Queries using Conversions, functions (to_char, to_num, and to_date),
string function (Conactenation, lpad, rpad, ltrim, rtrim, lower, upper,
initcap, length, substr, and instr), date functions (sysdate, next_day,
add_months, last_day, months_between, least, greatest, trunk, round,
to_char, to_date).
TABLE DEFINITIONS
Branch Schema <branch-name, branch-city, assets>
Customer Schema <customer-name, customer-street, customer-city>
Loan Schema <loan-number, branch-name, amount>
Borrower Schema <customer-name, loan-number>
33
DataBaseManagementSystems
LAB MANUAL
BRANCH TABLE
Branch Name
Brighton
Downtown
Mianus
North Town
Perryridge
Pownal
Redwood
Round Hill
Branch City
Brooklyn
Brooklyn
Horseneck
Rye
Horseneck
Bennington
Palo Alto
Horseneck
Assets
7100000
9000000
400000
3700000
1700000
300000
2100000
800000
Customer Street
Spring
Senator
North
Sand Hill
Walnut
Main
Alma
Main
Park
North
Putnam
Nassau
Customer City
Pittsfield
Brooklyn
Rye
Woodside
Stamford
Harrison
Palo Alto
Harrison
Pittsfield
Rye
Stamford
Princeton
Branch Name
Round Hill
Downtown
Perryridge
Perryridge
Downtown
Redwood
Mianus
Amount
900
1500
1500
1300
1000
2000
500
CUSTOMER TABLE
Customer Name
Adams
Brooks
Curry
Glenn
Green
Hayes
Johnson
Jones
Lindsay
Smith
Turner
Williams
LOAN TABLE
Loan Number
L-11
L-14
L-15
L-16
L-17
L-23
L-93
34
DataBaseManagementSystems
LAB MANUAL
BORROWER TABLE
Customer Name
Adams
Curry
Hayes
Jackson
Jones
Smith
Smith
Williams
Loan Number
l-16
L-93
L-15
L-14
L-17
L-11
L-23
L-17
ACCOUNT TABLE
Account Number
A-101
A-102
A-201
A-215
A-217
A-222
A-305
Branch Name
Downtown
Perryridge
Brighton
Mianus
Brighton
Redwood
Round Hill
Balance
500
400
900
700
750
700
350
DEPOSITOR TABLE
Customer Name
Hayes
Johnson
Johnson
Jones
Lindsay
Smith
Turner
Account Number
A102
A-101
A-201
A-217
A-222
A-215
A-305
QUERIES
1) To list all the fields from the table Customer.
SELECT branch_name
FROM Loan;
35
DataBaseManagementSystems
LAB MANUAL
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
FROM Loan
WHERE amount NOT BETWEEN 90000 AND 100000;
36
DataBaseManagementSystems
LAB MANUAL
8) For all customers who have a loan from the bank, find their names, loan
substring Main.
SELECT customer_name
FROM Customer
WHERE customer_street LIKE %Main%;
37
DataBaseManagementSystems
LAB MANUAL
12) To list in alphabetic order all customers who have a loan at the
Perryridge branch.
SELECT DISTINCT customer_name
FROM Borrower B, Loan L
WHERE B.loan_number = L.loan_number
AND branch_name = Perryridge
ORDER BY customer_name;
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);
38
DataBaseManagementSystems
LAB MANUAL
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
FROM Borrower);
18) To find all customers who have an account but no loan at the bank,
without duplicates.
(SELECT DISTINCT customer_name
FROM Depositor)
EXCEPT
(SELECT customer_name
FROM Borrower);
19) To find all customers who have an account but no loan at the bank, with
duplicates.
(SELECT DISTINCT customer_name
FROM Depositor)
EXCEPT ALL
(SELECT customer_name
FROM Borrower);
SELECT AVG(balance)
FROM Account
GROUP BY branch_name;
22) Find the number of depositors for each branch .
DataBaseManagementSystems
LAB MANUAL
SELECT customer_name
FROM Borrower
WHERE customer_street IN (SELECT customer_name
40
DataBaseManagementSystems
LAB MANUAL
FROM Depositor);
29) Find all customers who have both an account and a loan at the
Perryridge branch
SELECT DISTINCT B.customer_name
FROM Borrower B, Loan L
WHERE B.loan_number L.loan_number
AND branch_name = Perryridge
AND (branch_name, customer_name) IN
(SELECT branch_name, customer_name
FROM Depositor D, Account A
WHERE D.account_number = A.account_number);
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
31) Find the names of customers who do have a loan at the bank, and
DataBaseManagementSystems
LAB MANUAL
34) Find all customers who have an account at all the branches located in
Brooklyn.
SELECT DISTINCT S.customer_name
FROM Depositor AS D
WHERE NOT EXISTS ((SELECT branch_name
FROM Branch
WHERE branch_city = Brroklyn)
EXCEPT
(SELECT R.branch_name
FROM Depositor AS T, Account AS R
WHERE T.account_number =
R.account_number
AND D.customer_name = t.customer_name));
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.
SELECT DISTINCT T.customer_name
42
DataBaseManagementSystems
LAB MANUAL
FROM Depositor AS T
WHERE NOT 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);
37) Find the average account balance of those branches where the average
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
43
DataBaseManagementSystems
LAB MANUAL
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.
6) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and
MIN), GROUP BY, HAVING and Creation and Dropping of Views.
7) Queries using Conversions, functions (to_char, to_num, and to_date),
string function (Conactenation, lpad, rpad, ltrim, rtrim, lower, upper,
initcap, length, substr, and instr), date functions (sysdate, next_day,
add_months, last_day, months_between, least, greatest, trunk, round,
to_char, to_date).
DataBaseManagementSystems
LAB MANUAL
STRING FUNCTIONS:
17) To display a field value after left padding.
SELECT LPAD('PAGE-1', 10, '*') FROM DUAL;
18) To display a field value after left padding.
SELECT RPAD('PAGE-1', 10, '*') FROM DUAL;
19) To display a field value after converting to lower case.
SELECT LOWER(A) FROM DUAL;
20) To display a field value after converting to upper case.
SELECT LOWER(a) FROM DUAL;
21) To display a field value after converting to initial capital case.
SELECT INITCAP(HOW ARE YOU?) FROM DUAL;
45
DataBaseManagementSystems
LAB MANUAL
WEEK 8 (PL/SQL)
6) (i) Creation of simple PL/SQL program which includes declaration
section, executable section and exception handling section ( ex:
Student marks can be selected from the table and printed for those
who secured first class and an exception can be raised if no records
were found).
(ii) Insert data into student table and use COMMIT, ROLLBACK
and SAVEPOINT in SQL block.
7) Develop a program that includes the features NESTED IF, CASE
and CASE expression. The program can be extended using the
NULLIF and COALESCE functions.
8) Program development using WHILE LOOPS, numeric FOR
LOOPS, nested loops using ERROR handling, BUILT IN exceptions,
USER defined exceptions, RAISE APPLICATION ERROR.
46
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
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
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.
48
DataBaseManagementSystems
LAB MANUAL
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;
/
counter
counter
counter
counter
counter
10
8
6
4
2
PS:
Reverse For syntax:
For <var> in reverse <start_num> .. <endnum> loop
<statement(s);>
End loop;
Other forms of if syntax are:
If <condition> then
<action(s);>
End if;
If <condition> then
<action(s);>
Else
<action(s);>
End if;
If <condition> then
<action(s);>
Elsif <condition> then
<action(s);>
else
49
DataBaseManagementSystems
LAB MANUAL
<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;
end;
/
set serveroutput off
counter
counter
counter
counter
counter
counter
counter
counter
3
4
5
6
7
8
9
10
50
DataBaseManagementSystems
LAB MANUAL
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);
while cnt <= 10 loop dbms_output.put_line(loop counter: || to_char(cnt, 999));
cnt := cnt + 1;
end loop;
end;
/
set serveroutput off
counter
counter
counter
counter
counter
counter
counter
counter
:
:
:
:
:
:
:
:
3
4
5
6
7
8
9
10
51
DataBaseManagementSystems
LAB MANUAL
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
prompt Enter Employee Number:
accept n
declare
dname emp.emp_name%type;
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;
/
52
DataBaseManagementSystems
LAB MANUAL
employee details
Name:allen
basic:9500
desig:mech
PS:
Similarly you can use other SQL statements in the PL/SQL block
Exercises:
1) Write a PL/SQL code, EX_INVNO.SQL, block for
inverting a number using all forms of loops.
ANSWER:declare
n number(20):=123;
s number(13):=0;
d number(3):=1;
r number(3):=10;
begin
dbms_output.put_line('the number is :' || n);
while n>0 loop
d:=mod(n,10);
s:=(s*r)+d;
53
DataBaseManagementSystems
LAB MANUAL
n:=n/r;
end loop;
dbms_output.put_line('inverted values' || s);
end;
/
OUTPUT:the number is:123
inverted value is:321
2) Write a PL/SQL code, EX_SUMNO.SQL that prints
the sum of n natural numbers.
ANSWER:prompt enter number:
accept number n
declare
isum number(2):=0;
i number;
n number:=&n;
begin
for i in 1..n loop
isum:=isum+i;
54
DataBaseManagementSystems
LAB MANUAL
end loop;
dbms_output.put_line('sum is ' || isum);
end;
/
OUTPUT:enter the number:7
sum is 28
DataBaseManagementSystems
LAB MANUAL
is
is
is
is
is
:27
:48
:75
:108
:147
DataBaseManagementSystems
LAB MANUAL
14)
Develop a program that includes the features NESTED IF,
CASE and CASE expression. The program can be extended using the
NULLIF and COALESCE functions.
15)
Program development using WHILE LOOPS, numeric FOR
LOOPS, nested loops using ERROR handling, BUILT IN exceptions,
USER defined exceptions, RAISE APPLICATION ERROR.
16)
Program development using creation of procedure, passing
parameters IN and OUT procedures.
17)
Program development using creation of stored function, invoke
functions in SQL statements and write complex functions.
18)
Program development using creation of package specification,
package bodies, private objects, package variables and cursors and
calling stored packages.
19)
Develop programs using features of parameters in a CURSOR,
FOR UPDATE CURSOR, WHERE CURRENT of clause and
CURSOR variables.
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.
1. Create the table NEWEMP <emp_no, emp_name, join_date, basic).
2. Open an editor and type the following program.
Program
prompt Enter Employee Number:
57
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
into
from
where
DataBaseManagementSystems
LAB MANUAL
if sql%rowcount > 0
then
insert into
newemp
values
(dno, dname, ddate, dbasic);
dbms_output.put_line(Record inserted into NEWEMP);
dbms_output.put_line(DNO || || DNAME || || DDATE || ||
DBASIC);
end if;
exception
when no_data_found then
dbms_output.put_line (Record || &userno || does not exist);
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
tax
name
number(10, 2);
number(10, 2);
varchar2(30);
begin
select
into
from
where
emp_name, basic
name, tot_basic
emp
emp_no = &userno;
DataBaseManagementSystems
LAB MANUAL
PS:
EXECPTIONS
When a program is executed certain errors are automatically recognized and
certain error situations must be recognized by the program itself. Errors in
general are referred to as Exceptions.
Exceptions can be either System defined or User defined.
Certain system exceptions raise the following flags:
CURSOR_ALREADY_OPEN Displayed when the user tries to open a cursor
that is already open
DUP_VAL_ON_INDEX when user tries to insert a duplicate value into a
unique column
INVALID_CURSOR when user references an invalid cursor or attempts an
illegal cursor operation
INVALID_NUMBER when user tries to use something other than a number
where one is called for
LOGIN_DENIED when connect request for user has been denied
NO_DATA_FOUND this flag becomes TRUE when SQL select statement
failed to retrieve any rows
NOT_LOGGED_ON user is not connected to ORACLE
PROGRAM_ERROR user hits a PL/SQL internal error
STORAGE_ERROR user hits a PL/SQL memory error
TIMEOUT_ON_RESOURCE user has reached timeout while waiting for an
Oracle resource
TRANSACTION_BACKED_OUT a remote server has rolled back the
transaction
TOO_MANY_ROWS the flag becomes TRUE when SQL select statement
retrieves more than one row and it was supposed to retrieve only 1 row
VALUE_ERROR user encounters an arithmetic, conversion, truncation or
constraint error
60
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
printed for those who secured first class and an exception can be
raised if no records were found).
(ii) Insert data into student table and use COMMIT, ROLLBACK
and SAVEPOINT in SQL block.
21)
Develop a program that includes the features NESTED IF,
CASE and CASE expression. The program can be extended using the
NULLIF and COALESCE functions.
22)
Program development using WHILE LOOPS, numeric FOR
LOOPS, nested loops using ERROR handling, BUILT IN exceptions,
USER defined exceptions, RAISE APPLICATION ERROR.
23)
Program development using creation of procedure, passing
parameters IN and OUT procedures.
24)
Program development using creation of stored function, invoke
functions in SQL statements and write complex functions.
25)
Program development using creation of package specification,
package bodies, private objects, package variables and cursors and
calling stored packages.
26)
Develop programs using features of parameters in a CURSOR,
FOR UPDATE CURSOR, WHERE CURRENT of clause and
CURSOR variables.
Example: 1
Create a PL/SQL program using cursors, to retrieve first tuple from the
department relation.
(use table dept(dno, dname, loc))
62
DataBaseManagementSystems
LAB MANUAL
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;
dbms_output.put_line('vdno = ' ||vdno|| ' vdname = '||vdname||' vloc
= '||vloc);
close c1;
end;
/
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).
Syntax to define a cursor:
CURSOR <CURSOR-NAME> IS <SELECT STATEMENT>
Syntax to open the cursor:
OPEN <CURSOR-NAME>
Syntax to store data in the cursor:
FETCH <CURSOR-NAME> INTO <VAR1>, <VAR2>, <VAR3>.
OR
FETCH <CURSOR-NAME> INTO <RECORD-NAME>
Syntax to close the cursor:
CLOSE <CURSOR-NAME>
63
DataBaseManagementSystems
LAB MANUAL
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
for vdept in c1 loop
dbms_output.put_line('vdno = ' ||vdept.deptno|| ' vdname = '||
vdept.dname||' vloc = '||vdept.loc);
end loop;
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.
Syntax for cursor FOR LOOP:
FOR <VARIABLE> IN <CURSOR-NAME> LOOP
<STATEMENTs>
END LOOP;
Example: 3
64
DataBaseManagementSystems
LAB MANUAL
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;
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
65
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
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;
exit when cur_mgr%notfound;
ctr := ctr + 1;
dbms_output.put_line(ctr || Record inserted into
NEWEMP);
dbms_output.put_line(dno || || dname || ddate);
insert into new emp
values (dno, dname, ddate);
end loop;
if cur_mgr%rowcount = 0
then
close cur_mgr;
raise no_manager_found;
end if;
dbms_output.put_line(TOTAL number of records || ctr);
close cur_mgr;
exception
when no_manager_found then
dbms_output.put_line(NO RECORS FOUND);
end;
68
DataBaseManagementSystems
LAB MANUAL
/
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.
2) Code a program to calculate Tax for any employee whose number is
input from the keyboard. Display appropriate error message if data
does not exist in the table.
WEEK 11 (PL/SQL)
27)
(i) Creation of simple PL/SQL program which includes
declaration section, executable section and exception handling
section ( ex: Student marks can be selected from the table and
printed for those who secured first class and an exception can be
raised if no records were found).
(ii) Insert data into student table and use COMMIT,
ROLLBACK and SAVEPOINT in SQL block.
28)
Develop a program that includes the features NESTED IF,
CASE and CASE expression. The program can be extended using the
NULLIF and COALESCE functions.
29)
Program development using WHILE LOOPS, numeric FOR
LOOPS, nested loops using ERROR handling, BUILT IN exceptions,
USER defined exceptions, RAISE APPLICATION ERROR.
30)
Program development using creation of procedure, passing
parameters IN and OUT procedures.
31)
Program development using creation of stored function, invoke
functions in SQL statements and write complex functions.
32)
Program development using creation of package specification,
package bodies, private objects, package variables and cursors and
calling stored packages.
69
DataBaseManagementSystems
LAB MANUAL
33)
Develop programs using features of parameters in a CURSOR,
FOR UPDATE CURSOR, WHERE CURRENT of clause and
CURSOR variables.
Example: 1
Code a procedure to calculate the sales made to a particular customer.
{ create table trn (itmid number(10),
cstid number(10),
trnqty number(10));
create table itmmast (itmid
itmprice
number(10),
number(10,2));
DataBaseManagementSystems
LAB MANUAL
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;
/
Step 3: Save the TOTSALES.SQL file.
Step 4: Return to SQL Prompt and compile as
SQL> start TOTSALES; (press enter)
Step 5: On the screen you will get the message Procedure created. If you have
errors type
SQL> show errors
Step 6: To execute the procedure at SQL prompt type
SQL> variable sl number
SQL> execute totsales(2001, :sl)
SQL> print sl
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.
Various types of procedural objects are: Procedures, Functions, Packages.
Procedures:
Procedures are sub-programs, which will perform an action and functions are
subprograms that are generally coded to compute some value.
71
DataBaseManagementSystems
LAB MANUAL
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.
The IN OUT parameter is used to pass values to the procedure being called and
it is used to pass values to the caller of the procedure. The IN OUT variable
behaves like a regular variable inside the procedure.
Functions:
Functions are also a collection of SQL and PL/SQL code which can return a
value to the caller.
Unlike procedures, functions can return a value to the caller. This value is
returned through the use of the RETURN keyword within the function. A
function can return a single value to the caller. Functions do not allow the OUT
and IN OUT arguments.
Packages:
Packages are groups of procedures, functions, variables and SQL statements in
a single unit.
It consists of the package definition/specification and package body.
A package specification consists of the list of functions, procedures, variables,
constants, cursors and exceptions that will be available to users of the package.
A package body consists of the PL/SQL blocks and specifications for all of the
public objects listed in the package specification. It may also include code that
is run every time the package is invoked, regardless of the part of the package
that is executed.
The name of the package body should be the same as the name of the package
specification.
To delete procedural objects:
SQL> drop procedure <procedure-name>
72
DataBaseManagementSystems
LAB MANUAL
Example: 2
Code a function to return the square of a given number.
Step 1: Open the editor
Step 2: Type the code below in a file named, SQR.
Program
CREATE OR REPLACE FUNCTION SQR
(NO NUMBER)
RETURN NUMBER
IS
BEGIN
return no*no;
END;
/
Step 3: To test the function:
a. At SQL prompt type:
SQL> select sqr(10) from dual;
b. At SQL prompt, type the following
SQL> variable sq number
SQL> execute :sq := sqr(10)
c. In the editor, type the following
set serveroutput on
begin
dbms_output.put_line(Square of 10 is || sqr(10));
end;
/
set serveroutput off
73
DataBaseManagementSystems
LAB MANUAL
Example: 3
Code a function to return the net salary of a given employee.
Program
CREATE OR REPLACE FUNCTION NETSAL
(id in salary.emp_no%type)
RETURN NUMBER
IS
netsal salary.basic%type;
BEGIN
select sum(basic) + sum(commission) sum(deduction)
into netsal
from salary
where emp_no = id;
return (netsal);
end;
/
To test the function:
At SQL prompt, type
SQL> variable sal number
SQL> execute :sal := netsal(1001)
SQL> print sal
Example: 4
Code a package
Step 1: Open the editor and create the package
Step 2: Type the code below in a file named, MAHEPACK.
74
DataBaseManagementSystems
LAB MANUAL
Program
CREATE OR REPLACE PACKAGE MAHEPACK
AS
function netsal
(id in salary.emp_no%type)
return number;
procedure tax
(id in salary.emp_no%type, tax out number);
procedure totsales
(cid in cstmast.cstid%type, sal out number);
END;
/
Step 3: Save the above file and open the editor to create the package body
Program
CREATE OR REPLACE PACKAGE BODY MAHEPACK
AS
function netsal
(id in salary.emp_no%type)
return number
is
netsal salary.basic%type;
begin
select sum(basic) + sum(commission) sum(deduction)
into netsal
from salary
where emp_no = id;
return (netsal);
end;
procedure tax
(id in salary.emp_no%type, tax out number)
is
netsalary number(10, 2);
begin
netsalary := netsal(id);
if netsalary < 2000
75
DataBaseManagementSystems
LAB MANUAL
then
tax := netsalary * 0.02;
elsif netsalary < 4000
then
tax := netsal * 0.04;
else
tax := netsalary * 0.01;
end if;
end;
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
sales := 0;
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;
76
DataBaseManagementSystems
LAB MANUAL
end;
END;
/
Step 4: Save the above file and to create the package, at SQL prompt type
SQL> start mpack
SQL> start mpackb
Step 5: To execute, at SQL prompt type
SQL> variable tx number
SQL> execute mahepack.tax(1001, :tx)
SQL> print tx
Or
SQL> variable nsal number
SQL> execute :nsal := mahepack.netsal(1001)
SQL> print nsal
PS:
Show Errors:
SHOW ERRORS is used to display the line number and error of the most recent
compilation errors.
SQL> SHOW ERRORS
Raise Application Error:
RAISE_APPLICATION_ERROR procedure is one of Oracles utilities which
help the user to manage the error conditions in the applications by specifying
user-defined error numbers and messages.
It takes 2 input parameters the error number (which must be between -20000
and -20999) and the error message to display.
It terminates the procedure execution, rolls back any effects of the procedure,
returns any user-specified error number and error message.
WEEK 12 (PL/SQL)
34)
(i) Creation of simple PL/SQL program which includes
declaration section, executable section and exception handling
section ( ex: Student marks can be selected from the table and
77
DataBaseManagementSystems
LAB MANUAL
printed for those who secured first class and an exception can be
raised if no records were found).
(ii) Insert data into student table and use COMMIT,
ROLLBACK and SAVEPOINT in SQL block.
35)
Develop a program that includes the features NESTED IF,
CASE and CASE expression. The program can be extended using the
NULLIF and COALESCE functions.
36)
Program development using WHILE LOOPS, numeric FOR
LOOPS, nested loops using ERROR handling, BUILT IN exceptions,
USER defined exceptions, RAISE APPLICATION ERROR.
37)
Program development using creation of procedure, passing
parameters IN and OUT procedures.
38)
Program development using creation of stored function, invoke
functions in SQL statements and write complex functions.
39)
Program development using creation of package specification,
package bodies, private objects, package variables and cursors and
calling stored packages.
40)
Develop programs using features of parameters in a CURSOR,
FOR UPDATE CURSOR, WHERE CURRENT of clause and
CURSOR variables.
Example: 1
Write a row trigger to insert the existing values of the salary table into a new
table when the salary table is updated.
(Salary < emp_no, basic, commission, deduction, salary_date, department>
Salaryaud < emp_no, basic, commission, deduction, salary_date, department>)
Step 1: Open the editor
Step 2: Type the code below in a file named, TRSAL.
Program
CREATE TRIGGER UPDSAL
BEFORE UPDATE ON SALARY
78
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DECLARE
total_sal
number(9);
BEGIN
insert into emp
values (1009, Ram, 1000);
SAVEPOINT no_update;
update emp
set sal = sal + 2000
where emp_id = 1001;
update emp
set sal = sal + 1500
where emp_id = 1002;
select sum(sal)
into total_sal
from emp;
if total_sal > 20000
then
ROLLBACK TO SQVEPOINT no_update;
end if;
COMMIT;
END;
/
PS:
The above program first inserts a record into emp table. It then marks and saves
the current position in the transaction by using the SAVEPOINT. It updates the
salaries, if the salaries are exceeding 20000 it rollsback to the save point, ie
ignores the 2 updates and only commits the insert. If the salaries do not exceed
20000 then the insert and 2 updates are committed.
Example: 4
80
DataBaseManagementSystems
LAB MANUAL
Write a PL/SQL code of block, to calculate the area of the circle for the
values of radius varying from 1 to 10. Store the odd radius values and the
corresponding areas in a table.
Program
declare
pi constant number(4,2) := 3.14;
radius number(5);
areaa number(14,2);
begin
radius := 1;
while radius <= 10 loop
areaa := pi*power(radius,2);
case
when radius = 1
then
insert into area values (radius, areaa);
when radius = 3
then
insert into area values (radius, areaa);
when radius = 53
then
insert into area values(radius,areaa);
when radius = 7
then
insert into area values(radius,areaa);
when radius = 9
then
insert into area values(radius,areaa);
else
dbms_output.put_line(EVEN RADIUS, NOT
INSERTING!!!);
end case;
radius:=radius+1;
end loop;
end;
/
81
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
83
DataBaseManagementSystems
LAB MANUAL
Null?
Type
--------------------------------- --------
----------------------------
PNAME
NOT NULL
VARCHAR2(20)
DOJ
NOT NULL
DATE
84
DataBaseManagementSystems
LAB MANUAL
DOB
NOT NULL
DATE
SEX
NOT NULL
VARCHAR2(1)
PROF1
VARCHAR2(20)
PROF2
VARCHAR2(20)
SALARY
NUMBER(7,2)
NOT NULL
Single-row insert
DataBaseManagementSystems
LAB MANUAL
FROM S
Other Examples:
INPUT:
SQL>Insert into prog values (kkk,05-may-56);
RESULT: 1 row created.
INPUT:
SQL>Insert into prog20 values(Hema,25-sept-0128-jan-85,f,c,c+
+,25000);
RESULT: 1 row created.
INPUT:
SQL>Insert into prog values(&pname,&doj);
SQL> Insert into prog values('&pname','&doj');
Enter value for pname: ravi
Enter value for doj: 15-june-81
RESULT:
old 1: Insert into prog values('&pname','&doj')
86
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
88
DataBaseManagementSystems
LAB MANUAL
2. ROLLBACK
Undo work done (transactional).
Syntax:
ROLLBACK [WORK] [TO
[SAVEPOINT]'savepoint_text_identifier'];
ROLLBACK [WORK] [FORCE 'force_text'];
FORCE - will manually rollback an in-doubt distributed transaction
INPUT:
SQL>rollback;
RESULT:Rollback complete.
3. SAVEPOINT
Save changes to a point (transactional).
Syntax:
SAVEPOINT text_identifier
Example:
UPDATE employees
SET salary = 95000
WHERE last_name = 'Smith';
SAVEPOINT justsmith;
UPDATE employees
SET salary = 1000000;
SAVEPOINT everyone;
SELECT SUM(salary) FROM employees;
ROLLBACK TO SAVEPOINT justsmith;
89
DataBaseManagementSystems
LAB MANUAL
COMMIT;
90
DataBaseManagementSystems
LAB MANUAL
Null?
Type
----------------------- ------------------------NOT NULL
NUMBER(4)
VARCHAR2(10)
VARCHAR2(9)
NUMBER(4)
DATE
NUMBER(7,2)
NUMBER(7,2)
NUMBER(3)
NUMBER(3)
NUMBER(10)
Null?
--------------------NOT NULL
Type
--------------------------NUMBER(2)
VARCHAR2(14)
VARCHAR2(13)
DataBaseManagementSystems
LAB MANUAL
EMPNO ENAME
JOB
MGR HIREDATE SAL COMM DEPTNO
AGE ESAL
-------- ---------- --------- ---------- --------- ---------- ---------- ---------- -------------------------7369
SMITH
CLERK
7902 17-DEC-80 800
0
20
25
0
7499 ALLEN SALESMAN 7698 20-FEB-81 1600
300
30
25
0
7521 WARD SALESMAN 7698 22-FEB-81 1250
500
30
25
0
7566 JONES MANAGER 7839 02-APR-81 2975
500
20
25
0
7698 BLAKE MANAGER 7839 01-MAY-81 2850
1400
30
25
0
4.List all employee names and their salaries, whose salary lies between
1500/- and 3500/- both inclusive.
INPUT
SQL>select ename from emp where sal between 1500 and 3500;
RESULT
ENAME
---------ALLEN
JONES
BLAKE
CLARK
SCOTT
TURNER
FORD
russel
greg
9 rows selected.
5. List all employee names and their and their manager whose manager is
7902 or 7566 0r 7789.
92
DataBaseManagementSystems
LAB MANUAL
93
DataBaseManagementSystems
LAB MANUAL
7. List all employee names and jobs, whose job title includes M or P.
INPUT SQL>select ename,job from emp where job like M% or job like P
%;
RESULT:
ENAME
JOB
---------- --------JONES
MANAGER
BLAKE
MANAGER
CLARK MANAGER
KING
PRESIDENT
8. List all jobs available in employee table.
INPUT SQL>select distinct job from emp;
RESULT:
JOB
--------ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
assistant
clerk
7 rows selected.
9. List all employees who belongs to the department 10 or 20.
INPUT SQL>select ename from emp where deptno in (10,20);
RESULT:
ENAME
---------SMITH
JONES
CLARK
SCOTT
KING
94
DataBaseManagementSystems
LAB MANUAL
ADAMS
FORD
MILLER
8 rows selected.
10. List all employee names , salary and 15% rise in salary.
INPUT SQL>select ename , sal , sal+0.15* sal from emp;
RESULT:
ENAME
---------SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SAL
---------800
1600
1250
2975
1250
2850
2450
SAL+0.15*SAL
-----------920
1840
1437.5
3421.25
1437.5
3277.5
2817.5
7 rows selected.
11. List minimum , maximum , average salaries of employee.
INPUT SQL>select min(sal),max(sal),avg(sal) from emp;
RESULT:
MIN(SAL) MAX(SAL)
AVG(SAL)
--------------------------3
5000
1936.94118
12. Find how many job titles are available in employee table.
INPUT SQL>select count (distinct job) from emp;
RESULT:
COUNT(DISTINCTJOB)
-----------------7
95
DataBaseManagementSystems
LAB MANUAL
SAL
---------2975
2850
2450
15. Find how much amount the company is spending towards salaries.
INPUT SQL>select sum (sal) from emp;
RESULT
SUM(SAL)
--------32928
16. Display name of the dept. with deptno 20.
INPUT SQL>select ename from emp where deptno = 20;
RESULT
ENAME
---------SMITH
JONES
SCOTT
ADAMS
96
DataBaseManagementSystems
LAB MANUAL
---------CLARK
SCOTT
KING
ADAMS
JAMES
FORD
6 rows selected.
97
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
JOB
SUM(SAL)
-----------------ANALYST 6000
CLERK
23050
MANAGER 8275
PRESIDENT 5000
SALESMAN 5600
assistant
2200
clerk
2003
7 rows selected.
2. Display lowest paid employee details under each manager.
INPUT SQL>select ename, sal from emp where sal in (select min(sal) from
emp group by mgr);
RESULT
ENAME
SAL
------------------chai
3
JAMES
950
MILLER
1000
ADAMS
1100
russel
2200
5 rows selected.
3. Display number of employees working in each department and their
department name.
INPUT SQL> select dname, count (ename) from emp, dept where
emp.deptno=dept.deptno group by dname;
RESULT
DNAME
COUNT(ENAME)
------------------------ACCOUNTING
3
RESEARCH
5
SALES
9
4. Display the sales cost of package developed by each programmer.
INPUT SQL>select pname, sum(scost) from software group by pname;
99
DataBaseManagementSystems
LAB MANUAL
RESULT
PNAME
-------------------john
kamala
raju
3 rows selected.
SUM(SCOST)
---------12000
12000
12333
100
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
no rows selected
13. Display the details of software developed in c language by female
programmers of pragathi.
INPUT SQL>select software.pname, title, devin, scost, dcost, sold from
programmer, software, study where devin = c and sex =F and splace =
pragathi and programmer.pname = software.pname and software.pname =
study.pname;
103
DataBaseManagementSystems
LAB MANUAL
14. Which language has been stated by the most of the programmers as
proficiency one?
INPUT SQL>select prof1, count(*) from programmer group by prof1 having
count (*) = (select max (count (*) ) from programmer group by prof1);
Writing Nested Queries.
To write queries using Set operations and to write nested queries.
Set Operations:
UNION
INTERSECT
EXCEPT -
OR
-
AND
NOT
DataBaseManagementSystems
MARY
LAB MANUAL
4500 SABHARI
105
DataBaseManagementSystems
LAB MANUAL
3. How many packages were developed by the person who developed the
cheapest package.
INPUT SQL>select pname, count (title) from software where dcost = (select
min(dcost) from software) group by pname;
RESULT
PNAME
------------VIJAY
COUNT(TITLE)
---------------------1
DataBaseManagementSystems
LAB MANUAL
107
DataBaseManagementSystems
LAB MANUAL
108
DataBaseManagementSystems
LAB MANUAL
1 row updated.
Note: update command does not works for all queries on views.
INPUT SQL>delete from view1 where pname like raju;
RESULT
1 row deleted.
109
DataBaseManagementSystems
LAB MANUAL
View dropped;
View dropped;
DataBaseManagementSystems
LAB MANUAL
NETPAY1:=BASIC1+HRA1+DA1-PF1;
INSERT INTO EMPDET VALUES (ENO1, ENAME1, DEPTNO1,
BASIC1, HRA1, DA1, PF1, NETPAY1);
END;
RESULT:
SQL> @BASIC
Enter value for eno1: 104
old 11: ENO1:=&ENO1;
new 11: ENO1:=104;
Enter value for ename1: SRINIVAS REDDY
old 12: ENAME1:='&ENAME1';
new 12: ENAME1:='SRINIVAS REDDY';
Enter value for deptno1: 10
old 13: DEPTNO1:=&DEPTNO1;
new 13: DEPTNO1:=10;
Enter value for basic1: 6000
old 14: BASIC1:=&BASIC1;
new 14: BASIC1:=6000;
PL/SQL procedure successfully completed.
SQL>/
Enter value for eno1: 105
old 11: ENO1:=&ENO1;
new 11: ENO1:=105;
Enter value for ename1: CIRAJ
old 12: ENAME1:='&ENAME1';
new 12: ENAME1:='CIRAJ';
Enter value for deptno1: 10
old 13: DEPTNO1:=&DEPTNO1;
new 13: DEPTNO1:=10;
Enter value for basic1: 6000
old 14: BASIC1:=&BASIC1;
new 14: BASIC1:=6000;
111
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
num:=trunc(num/10);
End loop;
if (s=num1)then
dbms_RESULT.put_line(num1||' IS ARMSTRONG NUMBER ');
else
dbms_RESULT.put_line(num1||' IS NOT ARMSTRONG
NUMBER ');
End if;
END;
/
RESULT:
SQL>@arm
Enter value for num: 153
old 7: num:=#
new 7: num:=153;
153 IS ARMSTRONG NUMBER
PL/SQL procedure successfully completed.
SQL> /
Enter value for num: 123
old 7: num:=#
new 7: num:=123;
123 IS NOT ARMSTRONG NUMBER
PL/SQL procedure successfully completed.
Writing a PL/SQL block for checking a number even or odd.
AIM: To write a PL/SQL block to check whether a given number is Even
or Odd.
INPUT
DECLARE
num number(5);
rem number;
BEGIN
num:=#
113
DataBaseManagementSystems
LAB MANUAL
rem:=mod(num,2);
if rem=0
then
dbms_RESULT.put_line(' Number '||num||' is Even');
else
dbms_RESULT.put_line(' Number '||num||' is Odd');
end if;
END;
RESULT:
SQL>start even
Enter value for num: 6
old 5: num:=#
new 5: num:=6;
Number 6 is Even
PL/SQL procedure successfully completed.
SQL> /
Enter value for num: 3
old 5: num:=#
new 5: num:=3;
Number 3 is Odd
PL/SQL procedure successfully completed.
DataBaseManagementSystems
LAB MANUAL
DECLARE
num number(5);
rem number(5);
sm number(5):=0;
num1 number(5);
BEGIN
num:=#
num1:=num;
while(num>0)
loop
rem:=mod(num,10);
sm:=sm+rem;
num:=trunc(num/10);
end loop;
dbms_RESULT.put_line('SUM OF DIGITS OF '||num1||' IS: '||sm);
end;
/
RESULT:
SQL> @sum
INPUT truncated to 2 characters
Enter value for num: 123
old 7: num:=#
new 7: num:=123;
SUM OF DIGITS OF 123 IS: 6
PL/SQL procedure successfully completed.
SQL> @sum
INPUT truncated to 2 characters
Enter value for num: 456
old 7: num:=#
new 7: num:=456;
SUM OF DIGITS OF 456 IS: 15
PL/SQL procedure successfully completed.
115
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
34
PL/SQL procedure successfully completed.
DataBaseManagementSystems
LAB MANUAL
SQL> /
Enter value for name1: MADAM
old 6: name1:='&name1';
new 6: name1:='MADAM';
REVERSE OF STRING IS:MADAM
MADAM IS PALINDROME
PL/SQL procedure successfully completed.
DataBaseManagementSystems
LAB MANUAL
RESULT:
SQL> @abc
-----------------------------------------------------------------------------Department is :10
Department name is : ACCOUNTING
-----------------------------------------------------------------------------7782 CLARK 2450
7839 KING 5000
7934 MILLER 1300
----------------------------------------------------------------------------Total salary is: 8750
--------------------------------------------------------------------------------------------------------------------------------------------------------Department is :20 Department name is:RESEARCH
-----------------------------------------------------------------------------7369 SMITH 800
7566 JONES 2975
7788 SCOTT 3000
7876 ADAMS 1100
7902 FORD 3000
----------------------------------------------------------------------------Total salary is: 10875
----------------------------------------------------------------------------------------------------------------------------------------------------------Department is :30 Department name is:SALES
-----------------------------------------------------------------------------7499 ALLEN 1600
7521 WARD 1250
7654 MARTIN 1250
7698 BLAKE 2850
7844 TURNER 1500
7900 JAMES 950
119
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
dbms_RESULT.put_line(em);
end loop;
close c;
open c('ANALYST');
dbms_RESULT.put_line(' EMPLOYEES WORKING AS ANALYST
ARE:');
loop
fetch c into em;
exit when c%notfound;
dbms_RESULT.put_line(em);
end loop;
close c;
END;
RESULT:
EMPLOYEES WORKING AS MANAGERS ARE:
JONES
BLAKE
CLARK
EMPLOYEES WORKING AS ANALYST ARE:
SCOTT
FORD
PL/SQL procedure successfully completed.
DataBaseManagementSystems
LAB MANUAL
122
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
old 8: d:=&d;
new 8: d:=40;
Employee does not exist
PL/SQL procedure successfully completed.
DataBaseManagementSystems
LAB MANUAL
125
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
RESULT:
SQL> @trigger
Trigger created.
SQL> select * from dept;
DEPTNO DNAME
LOC
--------- -------------- ------------10 ACCOUNTING NEW YORK
20 RESEARCH
DALLAS
30 SALES
CHICAGO
40 OPERATIONS BOSTON
SQL> insert into dept values(&deptnp,'&dname','&loc');
Enter value for deptnp: null
Enter value for dname: marketing
Enter value for loc: hyd
old 1: insert into dept values(&deptnp,'&dname','&loc')
new 1: insert into dept values(null,'marketing','hyd')
insert into dept values(null,'marketing','hyd')
*
ERROR at line 1:
ORA-20001: error::deptno cannot be null
ORA-06512: at "SCOTT.TRIG1", line 5
ORA-04088: error during execution of trigger 'SCOTT.TRIG1'
SQL> /
Enter value for deptnp: 10
Enter value for dname: manager
Enter value for loc: hyd
old 1: insert into dept values(&deptnp,'&dname','&loc')
new 1: insert into dept values(10,'manager','hyd')
insert into dept values(10,'manager','hyd')
*
ERROR at line 1:
ORA-20002: error:: cannot have duplicate deptno
ORA-06512: at "SCOTT.TRIG1", line 9
ORA-04088: error during execution of trigger 'SCOTT.TRIG1'
127
DataBaseManagementSystems
LAB MANUAL
SQL> /
Enter value for deptnp: 50
Enter value for dname: MARKETING
Enter value for loc: HYDERABAD
old 1: insert into dept values(&deptnp,'&dname','&loc')
new 1: insert into dept values(50,'MARKETING','HYDERABAD')
1 row created.
SQL> select * from dept;
DEPTNO DNAME
LOC
--------- -------------- ------------10 ACCOUNTING NEW YORK
20 RESEARCH
DALLAS
30 SALES
CHICAGO
40 OPERATIONS BOSTON
50 MARKETING
HYDE
Locking Table.
AIM: To learn commands related to Table Locking
LOCK
TABLE
Statement
Manually
lock
one
or
more
tables.
Syntax:
LOCK TABLE [schema.] table [options] IN lockmode
MODE [NOWAIT]
128
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
130
DataBaseManagementSystems
LAB MANUAL
You will get the Welcome to the Form Builder window. If you dont want to
get this window anymore uncheck the Display at startup box. You can start
your work with any of the following options:
Use the data Block Wizard
Build a new form manually
Open an existing form
Build a form based on a template
The default is Use the data Block Wizard. If you want to build a new form
manually, click on "Cancel or check Build a new form manually and click
OK.
Connect to database
In the Object Navigator window, highlight "Database Objects." Go to the
Main menu and choose "File," then "Connect."
In the Connect window, login in as scott password tiger, then click
CONNECT.
Notice that the box next to Database Objects is not empty anymore and it has
a + sign in it. That will indicate that this item is expandable and you are able
to see its entire objects.
Click on the + sign next to the Database Objects to expand all database
schemas.
Create a Module
In the Object Navigator window, highlight module1. This is a default name.
Go to the Main menu and choose File, select Save as to store the new
object in the iself folder and save it as customer data entry. "c:_de." In this
example the DE abbreviation stands for Data Entry.
Create a Data Block
In the Object Navigator window, highlight "Data Blocks, and click on the
"create icon. The Create icon is in the vertical tool bar in the Object
Navigator window. It is a green + sign. If you drag your cursor on the icon a
tooltip will show Create.
131
DataBaseManagementSystems
LAB MANUAL
Layout Wizard
End of the Data Block Wizard and beginning of the Layout Wizard
In the Congratulations screen, use the default checkmark radio button (Create
the data block, then call the Layout Wizard), and click "Finish." You can also
use the Data Block Wizard to modify your existing data block. Simply select
the data block in the Object Navigator and click the Data Block Wizard toolbar
button, or choose Data Block wizard from the Tools menu.
Welcome screen
132
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
Type the "Frame Title" and click "next." Checkmark the Display Scrollbar box
when you use multiple records or the Tabular option.
Congratulation Screen
In the Congratulations window, click "Finish."
You will see the output layout screen.
Make some window adjustments and then run the form. To run the form, click
on the Run icon. The Run icon is on the horizontal toolbar in the
CUSTOMER_DE canvas.
The object module should be compiled successfully before executing the Form.
Execute Query
Click on the "Execute Query" icon below the main menu. If you drag the cursor
on the toolbar in the Forms Runtime window, a tooltip will be displayed and
you see Execute Query.
So to know all your option, drag your cursor to view all the icon descriptions.
Next Record
Click on the "Next Record" icon to navigate to the next record.
Previous Record
Click on the "Previous Record" icon to navigate to the previous record.
This is an easy way to navigate through the Customer table.
Enter Query
Click on the "Enter Query" icon to query selected records.
Insert Record
Click "Insert Record" to add new customer. All items on the forms will be
blanked. You can either type all the customer information or duplicate it from
pervious record.
134
DataBaseManagementSystems
LAB MANUAL
Duplicate Record
To duplicate the previous record, go to the main menu and select the Record
sub-menu. A drop down menu will be displayed. Select the Duplicate option
in the sub-menu.
Apply the changes. Remember in this stage, your record was inserted but not
committed yet.
Next and Previous Record
Click "next record" and "previous record" to navigate through the records and
the one was added.
Save transactions
Click "Save" to commit the insert statement.
Delete Record
Click "Remove Record" to delete the record.
Lock a Record
You can also lock the record.
Exit from Form Runtime
Exit the FORM Runtime. If you have not committed any transaction, you will
be prompted to save changes. Click YES to save changes.
Click OK for acknowledgement.
Dont forget to save the Form.
RABAD
135
DataBaseManagementSystems
LAB MANUAL
136
DataBaseManagementSystems
LAB MANUAL
Object wizard
137
DataBaseManagementSystems
LAB MANUAL
138
DataBaseManagementSystems
LAB MANUAL
139
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
In the Save as window, make sure to save the report in the ISELF folder and
name it "rpt01_stock_history, report number 1 stock history.
Data Model
In the Object Navigator, double click on the "Data Model" icon.
Create SQL box
In the Data Model window, click on the "SQL Query" icon. Then drag the plus
sign cursor and click it anywhere in the Data Model screen where you wish
your object to be.
In the SQL Query Statement window, write a query to read all the stocks
record sorted by their symbol.
(SQL Query Statement)
SELECT * FROM stocks
ORDER BY symbol
Click OK.
Change SQL boxs name
In the Data Model window, in the SQL box, right click on the Q_1 and open
its property palette.
In its property palette, change the name to Q_STOCKS. Then close the window.
Change GROUP boxs name
In the Data Model, right click on the group box (G_SYMBOL) and open its
property palette.
In the Group property palette, change the name to G_STOCKS, and close the
window.
Open Report Wizard
In the Data Model, click on the Report Wizard icon on the horizontal tool bar.
In the Style tab, on the Report Wizard window, type Stock History in the Title
box and choose the report style as Tabular.
Notice that when you change the report style a layout of that report will be
displayed on the screen.
Choose a different style to display its layout of its report style.
Data, Fields, Totals, Labels and Template tabs
141
DataBaseManagementSystems
LAB MANUAL
Click NEXT to go to the Data tab. In the SQL Query Statement verify your
query.
Click NEXT to navigate to the Fields tab, select the fields that you would like
to be display in your report. Select all the columns to be display.
Click NEXT to navigate to Totals tab, select the fields for which you would
like to calculate totals. We have none in this hands-on exercise.
Click NEXT to open the Labels tab, modify the labels and widths for your
fields and totals as desired.
Click NEXT again to go to the Template tab, and choose a template for your
report. Your report will inherit the templates colors, fonts, line widths, and
structure.
Use the default template and click finish.
Running a report
Now, you should have your output report on the screen.
Resize an object
Maximize the output report and format the report layout. To resize an object ,
select it and drag its handler to the preferred size.
Move an object
To move an object, select and drag it while the cursor is on the object.
This is a simple report.
Navigate through the output
To navigate through the output report in the Report Editor - Live Pre-viewer,
click on the "next page" or "previous page" icon on the horizontal toolbar.
Do the same with the "first page" or "last page" icon.
Use the zoom in and zoom out icon to preview the report.
Know reports functions
To know each icon functionalities, drag your cursor on it and a tooltip will
display its function.
Change Format Mask
To change the "format mask" of a column, the column should be selected. Then
go to the toolbar and click on the $ icon, "add decimal place," and the right
142
DataBaseManagementSystems
LAB MANUAL
justify format to the all currency columns (Todays Low, Todays High, and
current price)
Select the traded today column, and click on the ,0 icon (apply commas),
and make it right justify.
Also, you can change any attributes of field by opening its property palette. To
open an objects property palette, right click on it and select the Property Palette
option.
Right click on the "trade date" column and open its "property palette."
Change the date "Format Mask" property and make it year 2000 complaint
(MM-DD-RR).
143
DataBaseManagementSystems
LAB MANUAL
Creating reports
144
DataBaseManagementSystems
LAB MANUAL
145
DataBaseManagementSystems
LAB MANUAL
146
DataBaseManagementSystems
LAB MANUAL
147
DataBaseManagementSystems
LAB MANUAL
148
DataBaseManagementSystems
LAB MANUAL
149
DataBaseManagementSystems
LAB MANUAL
150
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
The roles CONNECT, RESOURCE and DBA are now deprecated (supported
only for backwards compatibility) unless you are still running Oracle 6.0
Error ORA-01927 "cannot REVOKE privileges you did not grant" - This
usually means you tried revoking permission from the table owner, e.g.
Oracle will not allow REVOKE select on USER1.Table1 from USER1 Owners
of objects ALWAYS have full permissions on those objects. This is one reason
it makes sense to place tables in one schema and the packaged prodecures used
to access those tables in a separate schema.
REFERENCES:
1. Oracle 9i Release 2 (9.2) SQL Reference,
www.cs.ncl.ac.uk/teaching/facilities/swdoc/oracle9i/server.920/a96540/to
c.htm.
2. Oracle 9i Release 1 (9.0.1) SQL Reference,
http://downloadeast.oracle.com/docs/cd/A91202_01/901_doc/server.901/a90125/toc.htm.
3. An A-Z Index of Oracle SQL Commands (version 9.2)
http://www.ss64.com/ora/.
4. Database Systems Instructor: Prof. Samuel Madden Source: MIT Open
Courseware (http://ocw.mit.edu).
5. RDBMS Lab Guide, www.campusconnect.infosys.com
userid:demo@infosys and passwork:infosys.
6. Orelly PL/SQL Pocket Reference,
http://www.unix.org.ua/orelly/oracle/langpkt/index.htm
7. PL/SQL User's Guide and Reference, Release 2 (9.2)
155
DataBaseManagementSystems
LAB MANUAL
http://www.lc.leidenuniv.nl/awcourse/oracle/appdev.920/a96624/toc
.htm.
156
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
The collections of entities of a particular entity type are grouped together into
an entity set.
20. What is Weak Entity set?
An entity set may not have sufficient attributes to form a primary key, and its
primary key compromises of its partial key and primary key of its parent entity,
then it is said to be Weak Entity set.
21. What is an attribute?
It is a particular property, which describes the entity.
22. What is a Relation Schema and a Relation?
A relation Schema denoted by R(A1, A2, , An) is made up of the relation
name R and the list of attributes Ai that it contains. A relation is defined as a set
of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each
tuple is an ordered list of n-values t=(v1,v2, ..., vn).
23. What is degree of a Relation?
It is the number of attribute of its relation schema.
24. What is Relationship?
It is an association among two or more entities.
25. What is Relationship set?
The collection (or set) of similar relationships.
26. What is Relationship type?
Relationship type defines a set of associations or a relationship set among a
given set of entity types.
27. What is degree of Relationship type?
It is the number of entity type participating.
28. What is DDL (Data Definition Language)?
A data base schema is specifies by a set of definitions expressed by a special
language called DDL.
29. What is VDL (View Definition Language)?
It specifies user views and their mappings to the conceptual schema.
160
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
shareable, and all the Oracle background processes and user processes can use
them.
The combination of the SGA and the Oracle background processes is known as
an Oracle instance
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?
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 filebut 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
169
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
DataBaseManagementSystems
LAB MANUAL
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
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
176
DataBaseManagementSystems
LAB MANUAL
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+
Algo.II Determining minimal K for relation schema R, given set of FDs F
1. Set K to R that is make K a set of all attributes in R
2. For each attribute A in K
a. Compute (K A)+ with respect to F
b. If (K A)+ = R then set K = (K A)+
106. What do you understand by dependency preservation?
Given a relation R and a set of FDs F, dependency preservation states that the
closure of the union of the projection of F on each decomposed relation Ri is
equal to the closure of F. i.e.,
((PR1(F)) U U (PRn(F)))+ = F+
if decomposition is not dependency preserving, then some dependency is lost in
the decomposition.
107. What is meant by Proactive, Retroactive and Simultaneous Update.
Proactive Update:
The updates that are applied to database before it becomes effective in real
world .
Retroactive Update:
The updates that are applied to database after it becomes effective in real
world .
Simulatneous Update:
The updates that are applied to database at the same time when it becomes
effective in real world .
108. What are the different types of JOIN operations?
Equi Join: This is the most common type of join which involves only equality
comparisions. The disadvantage in this type of join is that there
177
DataBaseManagementSystems
EMAIL:
LAB MANUAL
www.cserockz.com
Keep Watching for Regular Updates.!!
178