0% found this document useful (0 votes)
37 views57 pages

Dbms

The document describes database management systems lab experiments on data definition commands, data manipulation commands, and transaction control statements in SQL. It includes the syntax and use of commands like CREATE, ALTER, DROP, TRUNCATE, RENAME, INSERT, UPDATE, DELETE, SELECT, COMMIT, ROLLBACK, and SAVEPOINT. Programs provide examples of creating a table, inserting, updating, deleting and retrieving data from tables, and using transaction control statements.

Uploaded by

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

Dbms

The document describes database management systems lab experiments on data definition commands, data manipulation commands, and transaction control statements in SQL. It includes the syntax and use of commands like CREATE, ALTER, DROP, TRUNCATE, RENAME, INSERT, UPDATE, DELETE, SELECT, COMMIT, ROLLBACK, and SAVEPOINT. Programs provide examples of creating a table, inserting, updating, deleting and retrieving data from tables, and using transaction control statements.

Uploaded by

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

DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-1:
AIM: To explain Data Definition Commands, Data Manipulation Commands for inserting
and deleting data from Tables.
DESCRIPTION:
1. DDL COMMANDS:
● DDL is an acronym for DATA DEFINITION LANGUAGE.
● These commands are used for defining and managing database structures.
● It includes the following statements:
● CREATE
● ALTER
● DROP
● TRUNCATE
● RENAME
● CREATE:
● It is an DDL command.
● This command is used to create a new table in SQL.
● SYNTAX: CREATE TABLE table_name
(column_name1 data_type1,
column_name2 data_type2,
……
);
● ALTER:
● It is an DDL command.
● This command is used to add, delete or change columns in existing table in SQL.
● SYNTAX for ADDING COLUMN: ALTER TABLE table_name
ADD column_name data_type;
● SYNTAX for DROPING COLUMN: ALTER TABLE table_name
DROP COLUMN column_name;
● SYNTAX for MODIFYING COLUMN: ALTER TABLE table_name
MODIFY column_name data_type;
● DROP:
● It is an DDL command.
● This command is used to remove an existing table along with its structure
in SQL.
● SYNTAX: DROP TABLE table_name;
● TRUNCATE:
● It is an DDL command.
● This command is used to remove all rows from an existing table but structure
of table still exists in SQL.
● SYNTAX: TRUNCATE TABLE table_name;
● RENAME:
● It is a DDL command.
● It is used to change the name of a table in SQL.
● SYNTAX: RENAME <table_name> to <new_table_name>;

2. DML COMMANDS:
● DML is an acronym for DATA MANIPULATION LANGUAGE.

322103310140 1
DATABASE MANAGEMENT SYSTEMS LAB

● These commands are used to modify, manipulate data stored in database.


● It includes the following statements:
● INSERT
● UPDATE
● DELETE
● SELECT
● INSERT:
● It is an DML command.
● This command is used to insert a record in a new table in SQL.
● SYNTAX: INSERT INTO table_name (column_name1 ,column_name2 ,
) VALUES (value1 ,value2 ,
);
● UPDATE:
● It is an DML command.
● This command is used to update existing data within a table in SQL.
● SYNTAX: UPDATE table_name set column_name=value where condition;
● DELETE:
● It is an DML command.
● This command is used to delete single or multiple records from a table in SQL.
● SYNTAX: DELETE FROM table_name WHERE condition;
● SELECT:
● It is an DML command.
● This command is used removes all rows from an existing table but structure
of table still exists in SQL.
● SYNTAX: SELECT * FROM table_name;
SELECT column_name FROM table_name WHERE condition;
PROGRAMS:
CREATING A TABLE Employee:
SQL> CREATE TABLE Employee
2 (emp_id INT,
3 ename VARCHAR2(90),
4 esalary INT);

Table created.

INSERT VALUES INTO Employee table:


SQL> INSERT INTO Employee VALUES(140,'Viswa',50000);

1 row created.

SQL> INSERT INTO Employee VALUES(180,'Prasad',60000);

1 row created.

SQL> INSERT INTO Employee VALUES(162,'Chaitu',70000);

1 row created.

ALTERING THE TABLE:


ALTER TABLE Employee ADD age int;

322103310140 2
DATABASE MANAGEMENT SYSTEMS LAB

Table altered.

SQL> ALTER TABLE Employee DROP COLUMN age;

Table altered.

SQL> ALTER TABLE Employee MODIFY ename VARCHAR2(45);

Table altered.

UPDATING THE VALUES IN A TABLE:

SQL> UPDATE Employee SET emp_id=160 WHERE ename='Chaitu';

1 row updated.

SELECTING FROM A TABLE:


SQL> SELECT * FROM Employee;

EMP_ID ENAME ESALARY

140 Viswa 50000


180 Prasad 60000
160 Chaitu 70000
SQL> SELECT *FROM Employee WHERE esalary>55000;
EMP_ID ENAME ESALARY

180 Prasad 60000


160 Chaitu 70000

RENAMING A TABLE:
SQL> RENAME Employee to Emp;

Table renamed.

DELETING FROM A TABLE:


SQL> DELETE FROM Emp WHERE emp_id=180;

1 row deleted.

TRUNCATING A TABLE:
SQL> TRUNCATE TABLE Emp;

Table truncated.

DROPING A TABLE:
SQL> DROP TABLE Emp;

Table dropped.

322103310140 3
DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-2:
AIM: Data Manipulation Commands for updating and retrieving of data from Tables and
Transaction Control statements
DESCRIPTION:
1. DML COMMANDS:
● DML is an acronym for DATA MANIPULATION LANGUAGE.
● These commands are used to modify, manipulate data stored in database.
● It includes the following statements:
● INSERT
● UPDATE
● DELETE
● SELECT
● INSERT:
● It is an DML command.
● This command is used to insert a record in a new table in SQL.
● SYNTAX: INSERT INTO table_name (column_name1 ,column_name2 ,
) VALUES (value1 ,value2 ,
);
● UPDATE:
● It is an DML command.
● This command is used to update existing data within a table in SQL.
● SYNTAX: UPDATE table_name set column_name=value where condition;
● DELETE:
● It is an DML command.
● This command is used to delete single or multiple records from a table in SQL.
● SYNTAX: DELETE FROM table_name WHERE condition;
● SELECT:
● It is an DML command.
● This command is used removes all rows from an existing table but structure
of table still exists in SQL.
● SYNTAX: SELECT * FROM table_name;
SELECT column_name FROM table_name WHERE condition;
2. TCL COMMANDS:
● TCL is an acronym for TRANSACTION CONTROL LANGUAGE.
● These commands are used for managing and controlling transactions in a database
to maintain consistency.
● It includes the following statements:
● COMMIT
● ROLLBACK
● SAVEPOINT
● COMMIT:
● It is an TCL command.
● This command is used to save a given transaction into the database permanently.
● SYNTAX: COMMIT;
● ROLLBACK:
● It is an TCL command.
● This command is used to restore the data to the last committed state or savepoint.
● SYNTAX: ROLLBACK; or ROLLBACK savepoint_name;

322103310140 4
DATABASE MANAGEMENT SYSTEMS LAB

● SAVEPOINT:
● It is an TCL command.
● This command is used to save a transaction temporarily so that user can
easily rollbacked to that point whenever required.
● SYNTAX: SAVEPOINT savepoint_name;

PROGRAMS:
CREATE A TABLE SAILORS WHICH CONTAINS ATTRIBUTES SID, SNAME,
SRATING, SAGE.
SQL> CREATE TABLE sailors
2 (sid int,
3 sname varchar2(255),
4 srating int,
5 sage int);

Table created.
1) INSERT VALUES INTO TABLE SAILORS:
SQL> INSERT INTO sailors VALUES(22,'dustin',7,45);

1 row created.

SQL> INSERT INTO sailors VALUES(29,'lubber',8,33);

1 row created.

SQL> INSERT INTO sailors VALUES(31,'brutus',56);

1 row created.

2) UPDATE SAILORS TABLE BY MODIFYING NAME OF PARTICULAR SAILOR:

SQL> UPDATE sailors SET sname='dustbin' where

sid=22;

1 row updated.

SQL> SELECT * FROM sailors;

SID SNAME SRATING SAGE

22 dustbin 7 45
29 brutus 1 33
31 lubber 8 56

322103310140 5
DATABASE MANAGEMENT SYSTEMS LAB

3 rows selected.
DELETE A ROW FROM SAILORS TABLE
SQL> DELETE FROM sailors WHERE sid=22;

1 row deleted.

SQL> SELECT * FROM sailors;

SID SNAME SRATING SAGE

29 brutus 1 33
31 lubber 8 56
2rows selected.

3) RETRIVE NAME OF SAILOR WHOSE SID=35


SQL> SELECT sname from sailors where sage=35;

SNAME

lubber

4) ALL TCL COMMANDS


SQL> commit;

Commit
complete.

SQL> insert into sailors

values(40,'pavan',11,64);

1 row created.

SQL> savepoint a;

Savepoint created.

SQL> insert into sailors values(45,'maya',9,46);

1 row created.
SQL> SELECT * FROM sailors;

SID SNAME SRATING SAGE

29 brutus 1 33
31 lubber 8 56
40 pavan 11 64
45 maya 9 46

4 rows selected.

322103310140 6
DATABASE MANAGEMENT SYSTEMS LAB

SQL> rollback to a;

Rollback complete.

SQL> SELECT * FROM sailors;

SID SNAME SRATING SAGE

29 brutus 1 33
31 lubber 8 56
40 pavan 11 64
3 rows selected.

SQL> rollback;

Rollback complete.
SQL> SELECT * FROM sailors;

SID SNAME SRATING SAGE

29 brutus 1 33
31 lubber 8 56
2 rows selected.

322103310140 7
DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-3:
AIM: Basic functions like Numeric, String, Date, and conversion functions.
DESCRIPTION:
1. NUMERIC FUNCTIONS:
● ABS(X):
● This function returns the absolute value of X.
● SYNTAX: SELECT abs(x) FROM table_name;
● MOD(X,Y):
● The variable X is divided by Y and their remainder is returned.
● SYNTAX: SELECT mod(x,y) FROM table_name;
● SIGN(X):
● This returns 1 if X is positive, -1 if it is negative and 0 if the value of X is 0.
● SYNTAX: SELECT sign(x) FROM table_name;
● CEIL(X):
● This returns the smallest integer value that is either more than X or equal to it.
● SYNTAX: SELECT ceil(x) FROM table_name;
● FLOOR(X):
● This returns the largest integer value that is either less than X or equal to it.
● SYNTAX: SELECT floor(x) FROM table_name;
● POWER(X,Y):
● This function returns the value of X raised to the power of Y.
● SYNTAX: SELECT power(x,y) FROM table_name;
● LEAST(X,Y,Z,..):
● This function returns the value which is the smallest of the given numbers.
● SYNTAX: SELECT least(x,y,z,….) FROM table_name;
● GREATEST(X,Y,Z,…):
● This function returns the value which is the greatest of the given numbers.
● SYNTAX: SELECT greatest(x,y,z,….) FROM table_name;
● ROUND(X):
● This function returns the value rounded off to the next or the previous integer.
It means that if the decimal value is greater than 5 it rounds off to the next
integer and if it is less than 5 it rounds off to the previous integer.
● SYNTAX: SELECT round(x) FROM table_name;
2. STRING FUNCTIONS:
● ASCII(str):
● This function returns the ASCII or numeric value of the first word in the
string str provided. If it is an empty string, it returns 0.
● SYNTAX: SELECT ascii(x) FROM table_name;
● CONCAT(str1, str2):
● This function returns the string that forms by concatenating all the strings in
the argument list.
● SYNTAX: SELECT concat(str1,str2) FROM table_name;
● LENGTH(str):
● This function returns the length of the string str in bytes.
● SYNTAX: SELECT length(str) FROM table_name;
● LOWER(str):

322103310140 8
DATABASE MANAGEMENT SYSTEMS LAB

● All the characters in uppercase are converted to lowercase by this function.


● SYNTAX: SELECT lower(str) FROM table_name;
● UPPER(str):
● All the characters in uppercase are converted to lowercase by this function.
● SYNTAX: SELECT upper(str) FROM table_name;
● INITCAP(str):
●The first character of the string is converted into uppercase and the rest of
the string is left as it is.
● SYNTAX: SELECT initcap(str) FROM table_name;
● SUBSTR(str):
● Based on the n value the string is changed. The string returned will be of length n.
● SYNTAX: SELECT substr(str, n) FROM table_name;
● PAD(str, n, char):
● This function is the one which add the given character to the string so as to
make the length of the string equal to the value of the n given.
● There are two types of PAD():
1. LPAD()
2. RPAD()
● LPAD(str, n, char):
1. By using this function we can add the desired character on the
left side of the given string.
2. SYNTAX: SELECT lpad(str, n, char) FROM table_name;
● RPAD(str, n, char):
1. By using this function we can add the desired character on the
right side of the given string.
2. SYNTAX: SELECT rpad(str, n, char) FROM table_name;
● TRIM(str):
● This function is used to remove the extra spaces in the beginning and the
ending of string.
● There are two types of TRIM():
1. LTRIM()
2. RTRIM()
● LTRIM (str):
1. By using this function we can remove the extra spaces on the left
side of the string.
2. SYNTAX: SELECT ltrim(str) FROM table_name;
● RTRIM(str):
1. By using this function we can remove the extra spaces on the
right side of the given string.
2. SYNTAX: SELECT rtrim(str) FROM table_name;
● INSTR(str, char):
● This function returns first occurrence of character in astring.
● SYNTAX: SELECT instr (str, char) FROM table_name;
1. DATE FUNCTIONS:
● SYSDATE:
● This function returns the current date and time of the system. It is one of the
most popular oracle functions.
● SYNTAX: SELECT sysdate FROM table_name;
● ADD_MONTHS(d, n):

322103310140 9
DATABASE MANAGEMENT SYSTEMS LAB

● This function gives the same day as d, n number of months away. The value
of n can be positive or negative.
● SYNTAX: SELECT add_months(d,n) FROM table_name;
● MONTHS_BETWEEN(x, y):
● This function takes two values namely x and y which are in the form of
months. It returns the number of months between x and y.
● SYNTAX: SELECT months_between(x,y) FROM table_name;
● LAST_DAY(d):
● This function returns the last day of the month for the specific month d
provided in the function.
● SYNTAX: SELECT last_day(d) FROM table_name;
● NEXT_DAY(d, day):
● This function returns the next same day from the date given.
● SYNTAX: SELECT next_day(d,day) FROM table_name;
2. CONVERSION FUNCTIONS:
● TO_CHAR(n):
● TO_CHAR function is used to typecast a numeric or date input to character type
● SYNTAX: SELECT to_char(n) FROM table_name;
● TO_NUMBER(str, format):
● The TO_NUMBER function converts a character value to a numeric datatype.
● If the string being converted contains nonnumeric characters, the function
returns an error.
● SYNTAX: SELECT to_number(str, format) FROM table_name;
● TO_DATE(char, format):
● The function takes character values as input and returns formatted date
equivalent of the same.
● SYNTAX: SELECT to_date(char, format) FROM table_name;
PROGRAM:
1) NUMERIC FUNCTIONS:
SQL> SELECT abs(-99) FROM

dual; ABS(-99)

99
SQL> SELECT mod(25,7) FROM dual;

MOD(25,7)

4
SQL> SELECT sign(-5) FROM
dual; SIGN(-5)

-1

SQL> SELECT sign(5) FROM dual;

SIGN(5)

322103310140 10
DATABASE MANAGEMENT SYSTEMS LAB

1
SQL> SELECT sign(0) FROM dual;
SIGN(0)

0
SQL> SELECT floor(9.99) FROM dual;

FLOOR(9.99)

9
SQL> SELECT ceil(9.99) FROM dual;
CEIL(9.99)

10
SQL> SELECT power(9,9) FROM dual;

POWER(9,9)

387420489
SQL> SELECT least(10,4,15,6,7) FROM dual;
LEAST(10,4,15,6,7)

4
SQL> SELECT greatest(10,4,15,6,7) FROM dual;

GREATEST(10,4,15,6,7)

15
SQL> SELECT round(9.899) FROM dual;
ROUND(9.899)

10

2) STRING FUNCTIONS:

SQL> SELECT ascii('surya') FROM dual;


DATABASE MANAGEMENT SYSTEMS LAB
322103310140 11
DATABASE MANAGEMENT SYSTEMS LAB

ASCII('SURYA')

115
SQL> SELECT concat('surya', 'karthi') AS concat FROM dual;

CONCAT

suryakarthi
SQL> SELECT length('surya') FROM dual;
LENGTH('SURYA')

5
SQL> SELECT lower('KARTHI') AS low FROM dual;

LOW

karthi
SQL> SELECT upper('sun') AS upp FROM dual;
UPP
---
SUN
SQL> SELECT initcap('sun') AS ini FROM dual;

INI

---
Sun
SQL> SELECT instr('sun','u') FROM dual;
INSTR('SUN','U')

2
SQL> SELECT lpad('sun',10,'0000') AS lpad FROM dual;

LPAD

0000000sun
SQL> SELECT rpad('sun',10,'0000') AS rpad FROM dual;
RPAD

sun0000000
SQL> SELECT trim(' surya ') AS trim FROM dual;
TRIM
---
surya
SQL> SELECT ltrim(' surya ') AS ltrim FROM dual;
DATABASE MANAGEMENT SYSTEMS LAB
322103310140 12
DATABASE MANAGEMENT SYSTEMS LAB

LTRIM

surya
SQL> SELECT rtrim(' surya ') AS rtrim FROM dual;
RTRIM

Surya

3) DATE FUNCTIONS:
SQL> SELECT sysdate FROM dual;
SYSDATE

06-DEC-23
SQL> SELECT months_between(sysdate, '05-jan-24') FROM
dual; MONTHS_BETWEEN(SYSDATE,'05-JAN-24')

-.95615815
SQL> SELECT add_months(sysdate, 6) FROM dual;

ADD_MONTHS(SYSDATE,6)

06-JUN-24
SQL> SELECT last_day('25-jan-24') AS last_day FROM dual;
LAST_DAY

31-JAN-24
SQL> SELECT next_day(sysdate, 'fri') AS next_day FROM dual;

NEXT_DAY

08-DEC-23

322103310140 13
DATABASE MANAGEMENT SYSTEMS LAB

4) CONVERSION FUNCTIONS:
SQL> SELECT to_char(1234,'l9999') FROM dual;
TO_CHAR(1234,'l9999')

$1234
SQL> SELECT to_char(1234.56,'09999d9') FROM dual;

TO_CHAR(1234.56,'09999d9')

01234.6
SQL> SELECT to_char(12345,'99g999') FROM dual;
TO_CHAR(12345,'99G999')

12,345
SQL> SELECT to_char(12345,'xxxx') FROM dual;

TO_CHAR(12345,'XXXX’)

3039
SQL> SELECT to_char(12345,'s99999') FROM dual;
TO_CHAR(12345,'S99999')

+12345
SQL> SELECT to_char(123,'RN') FROM dual;

TO_CHAR(123,'RN’)

CXXIII
SQL> SELECT to_number('12345','99999') FROM dual;

TO_NUMBER('12345','99999')

12345
SQL> SELECT to_number('1234.5','9999.9') FROM dual;
TO_NUMBER('1234.5','9999.9')

1234.5

SQL> SELECT to_number('1,234.5','9,999.9') FROM dual;


DATABASE MANAGEMENT SYSTEMS LAB
322103310140 14
DATABASE MANAGEMENT SYSTEMS LAB

TO_NUMBER('1,234.5','9,999.9')

1234.5
SQL> SELECT to_number('a','x') FROM dual;

TO_NUMBER('A','X')

10
SQL> SELECT to_number('$123','$999') FROM dual;
TO_NUMBER('$123','$999')

123
SQL> SELECT to_date(sysdate,'dd-mm-yyyy') AS date FROM dual;

DATE

06-DEC-23

322103310140 15
DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-4:
AIM: Database Querying – Simple queries
DESCRIPTION:
A query can either be a request for data results from your database or for action on the data, or for
both. A query can give you an answer to a simple question, perform calculations, combine data from
different tables, add, change, or delete data from a database

PROGRAM:
CREATE A TABLE SAILORS WHICH CONTAINS ATTRIBUTES SID, SNAME,
SRATING, SAGE AND INSERTING VALUES IN IT

SQL> CREATE TABLE sailors


2 (sid int,
3 sname varchar2(90),
4 srating int,
5 sage int);

Table
created.

SQL> INSERT INTO sailors VALUES(22,'dustin',7,45);

1 row created.

SQL> INSERT INTO sailors VALUES(29,'brutus',1,33);

1 row created.

SQL> INSERT INTO sailors VALUES(31,'lubber',8,56);

1 row created.

SQL> INSERT INTO sailors VALUES(32,'andy',8,26);

1 row created.

SQL> INSERT INTO sailors VALUES (58,'rusty',10,36);

1 row created.

SQL> INSERT INTO sailors VALUES(64,'horatio',7,36);

1 row created.

SQL> INSERT INTO sailors VALUES(74,'horatio',9,35);

1 row created.

SQL> SELECT * FROM sailors;

322103310140 16
DATABASE MANAGEMENT SYSTEMS LAB

SID SNAME SRATING SAGE

22 dustin 7 45
29 brutus 1 33
31 lubber 8 56
32 andy 8 26
58 rusty 10 36
64 horatio 7 36
74 horatio 9 35

7 rows selected.

CREATE A TABLE BOATS WHICH CONTAINS ATTRIBUTES BID, BNAME,


BCOLOR AND INSERTING VALUES IN IT.

SQL> CREATE TABLE boats


2 (bid INT,
3 bname VARCHAR2(89),
4 bcolor

VARCHAR2(9)); Table

created.

SQL> INSERT INTO boats

VALUES(101,'interface','blue'); 1 row created.

SQL> INSERT INTO boats VALUES(102,'inter','red');

1 row created.

SQL> INSERT INTO boats

VALUES(103,'clipper','green'); 1 row created.

SQL> INSERT INTO boats VALUES(104,'Marine','red');

1 row created.

SQL> SELECT * FROM boats;

BID BNAME BCOLOR

101 interlake Blue


102 inter Red
103 clipper Green
104 Marine Red

4 rows selected.
DATABASE MANAGEMENT SYSTEMS LAB

322103310140 17
DATABASE MANAGEMENT SYSTEMS LAB

CREATE A TABLE RESERVES WHICH CONTAINS ATTRIBUTES BID, SID,


DAY AND INSERTING VALUES IN IT.

SQL> CREATE TABLE reserves


2 (sid INT,
3 bid INT,
4 day VARCHAR2(20));
Table created.
SQL> INSERT INTO reserves VALUES(22,101,'10-Oct-98');
1 row created.
SQL> INSERT INTO reserves VALUES(22,102,'10-Oct-98');
1 row created.
SQL> INSERT INTO reserves VALUES(22,103,'10-Aug-98');
1 row created.
SQL> INSERT INTO reserves VALUES(22,104,'10-Jul-98');
1 row created.
SQL> INSERT INTO reserves VALUES(31,104,'10-Dec-98');
1 row created.
SQL> INSERT INTO reserves VALUES(64,102,'10-Aug-98');
1 row created.
SQL> INSERT INTO reserves VALUES (74,103,'10-Aug-98');
1 row created.
SQL> SELECT * FROM
reserves; SID BID DAY

22 101 10-OCT-98
22 102 10-OCT-98
22 103 10-AUG-98
22 104 10-JUL-98
31 104 10-DEC-98
64 102 10-AUG-98
74 103 10-AUG-98

322103310140 18
DATABASE MANAGEMENT SYSTEMS LAB

1) Find all the sailors with rating above 9?


SQL> SELECT * FROM sailors WHERE

(srating>9); SID SNAME SRATING

SAGE

58 Rusty 10 36

2) Find the name of sailors with rating above 7?


SQL> select sname FROM sailors WHERE (srating>7);

SNAME

lubber
andy
rusty
Horatio

3) Find the name of the sailors who have reserved a green boat.
SQL> SELECT sname FROM sailors s,boats b,reserves r WHERE s.sid=r.sid and r.bid=b.bid and
b.bcolor=’green’;

SNAME

dustin
Horatio

4) Find the color of boat reserved by lubber


SQL> SELECT b.bcolor FROM boats b,reserves r , sailors s WHERE r.bid=b.bid and r.sid=s.sid and
s.sname=’lubber’;

BCOLOR

red

5) Find the names of the sailors who have reserved boat no 103?
SQL> SELECT sname FROM sailors s,reserves r WHERE s.sid=r.sid and r.bid=103;

SNAME

dustin
Horatio

6) Find all the sailors who have reserved atleast one boat
SQL> SELECT DISTINCT s.sname FROM sailors s ,reserves r WHERE s.sid=r.sid;

SNAME

lubber
dustin
Horatio
DATABASE MANAGEMENT SYSTEMS LAB
322103310140 19
DATABASE MANAGEMENT SYSTEMS LAB

7) Compute and increment the rating and display the name and sid of sailors who have
sailed 2 different boats on same day

SQL> SELECT DISTINCT s1.sname, s1.sid, s1.srating+1 as inc_rate FROM sailors s1, reserves r1,
reserves r2 WHERE r1.bid&lt;&gt;r2.bid and r1.sid =r2.sid and r1.day=r2.day and r1.sid=s1.sid;

SNAME SID INC_RATE

dustin 22 8

322103310140 20
DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-5:
AIM: Queries using aggregate functions, GROUP BY, and HAVING clauses.
DESCRIPTION:
1. AGGREGATE FUNCTIONS:
● An aggregate function performs a calculation on a set of values, and returns
a single value.
● Except for COUNT(*), aggregate functions ignore null values.
● There are 5 Aggregate Functions
● COUNT
● SUM
● AVG
● MAX
● MIN
● COUNT():
● This function is used to count the number of rows in a table.
● It can work on both numeric and non-numeric datatype and also considers
NULL values
● SYNTAX: SELECT count([ALL|DISTINCT]expression) FROM table_name;
● SUM():
● This function is used to calculate the sum of all selected columns in a table.
● It can work only on numeric datatype and don’t considers NULL values.
● SYNTAX: SELECT sum([ALL|DISTINCT]expression) FROM table_name;
● AVG():
● This function is used to calculate the avg of all selected columns in a table.
● It can work only on numeric datatype and don’t considers NULL values.
● SYNTAX: SELECT avg([ALL|DISTINCT]expression) FROM table_name;
● MAX():
● This function is used to return the maximum of all selected columns in a table.
● It can work only on numeric datatype and don’t considers NULL values.
● SYNTAX: SELECT max([ALL|DISTINCT]expression) FROM table_name;
● MIN():
● This function is used to return the minimum of all selected columns in a table.
● It can work only on numeric datatype and don’t considers NULL values.
● SYNTAX: SELECT min([ALL|DISTINCT]expression) FROM table_name;
2. GROUP BY CLAUSE:
● It combines the multiple records in single or more columns using some functions.
● SYNTAX: SELECT column_name(s)
FROM table_name
WHERE condition(s)
GROUP BY column_name(s)
ORDER BY column_name(s)
3. HAVING CLAUSE:
● The HAVING Clause enables you to specify conditions that filter which
group results appear in the results.
● The HAVING clause must follow the GROUP BY clause in a query.
● The WHERE clause places conditions on the selected columns, whereas the
HAVING clause places conditions on groups created by the GROUP BY
clause.

● SYNTAX: SELECT column_name(s)

322103310140 21
DATABASE MANAGEMENT SYSTEMS LAB

FROM table_name
WHERE condition(s)
GROUP BY
column_name(s) ORDER
BY column_name(s)
HAVING condition(s);
PROGRAM:
SQL>CREATE TABLE products
2 (
3 pno int,
4 pname varchar2(10),
5 price int,
6 quantity int
7 );

Table created.

SQL> INSERT INTO products(pno,pname,price,quantity)


VALUES(1,'DELL',50000,24); 1 row created.
SQL> INSERT INTO products(pno,pname,price,quantity)
VALUES(2,'HP',49000,22); 1 row created.
SQL> INSERT INTO products(pno,pname,price,quantity)
VALUES(3,'LENOVA',45000,30); 1 row created.
SQL> INSERT INTO products(pno,pname,price,quantity)
VALUES(4,'LENOVA',46000,15); 1 row created.
SQL> SELECT * FROM products;

PNO PNAME PRICE QUANTITY

1 DELL 50000 24
2 HP 49000 22
3 LENOVA 45000 30
4 LENOVA 46000 15

1) SUM():

SQL> SELECT sum(quantity) AS total_quantity FROM products;


TOTAL_QUANTITY

91

2) COUNT():

SQL> SELECT count(pno) AS total_no_of_products FROM products;


TOTAL_NO_OF_PRODUCTS
DATABASE MANAGEMENT SYSTEMS LAB
322103310140 22
DATABASE MANAGEMENT SYSTEMS LAB

3) AVG():

SQL> SELECT avg(price) FROM products;


AVG(PRICE)

47500

4) MAX():

SQL> SELECT max(price) FROM products;


MAX(PRICE)

50000

5) MIN():

SQL> SELECT min(price) FROM products;


MIN(PRICE)

45000

GROUP BY CLAUSE
SQL> SELECT pname, max(price) FROM products GROUP
BY pname; PNAME MAX(PRICE)

DELL 50000
HP 49000
LENOVA 46000

HAVING CLAUSE
SQL> SELECT pname,max(price) FROM products GROUP BY pname HAVING
max(price)<=47000;
PNAME MAX(PRICE)

LENOVA 46000

EXPERIMENT-6:
AIM: Database Querying – Nested queries, Sub-queries.
DATABASE MANAGEMENT SYSTEMS LAB
322103310140 23
DATABASE MANAGEMENT SYSTEMS LAB

DESCRIPTION:
A subquery, also known as an inner query or nested query, is a query embedded within another SQL
query.

PROGRAM:
CREATE A TABLE SAILORS WHICH CONTAINS ATTRIBUTES SID, SNAME,
SRATING, SAGE AND INSERTING VALUES IN IT

SQL> CREATE TABLE sailors


2 (sid int,
3 sname varchar2(90),
4 srating int,
5 sage int);

Table
created.

SQL> INSERT INTO sailors VALUES(22,'dustin',7,45);

1 row created.

SQL> INSERT INTO sailors VALUES(29,'brutus',1,33);

1 row created.

SQL> INSERT INTO sailors VALUES(31,'lubber',8,56);

1 row created.

SQL> INSERT INTO sailors VALUES(32,'andy',8,26);

1 row created.

SQL> INSERT INTO sailors VALUES (58,'rusty',10,36);

1 row created.

SQL> INSERT INTO sailors VALUES(64,'horatio',7,36);

1 row created.

SQL> INSERT INTO sailors VALUES(74,'horatio',9,35);

1 row created.

322103310140 24
DATABASE MANAGEMENT SYSTEMS LAB

SQL> SELECT * FROM sailors;


SID SNAME SRATING SAGE

22 dustin 7 45
29 brutus 1 33
31 lubber 8 56
32 andy 8 26
58 rusty 10 36
64 horatio 7 36
74 horatio 9 35

7 rows selected.

CREATE A TABLE BOATS WHICH CONTAINS ATTRIBUTES BID, BNAME,


BCOLOR AND INSERTING VALUES IN IT.

SQL> CREATE TABLE boats


2 (bid INT,
3 bname VARCHAR2(89),
4 bcolor

VARCHAR2(9)); Table

created.

SQL> INSERT INTO boats

VALUES(101,'interface','blue'); 1 row created.

SQL> INSERT INTO boats VALUES(102,'inter','red');

1 row created.

SQL> INSERT INTO boats

VALUES(103,'clipper','green'); 1 row created.

SQL> INSERT INTO boats VALUES(104,'Marine','red');

1 row created.

SQL> SELECT * FROM boats;

BID BNAME BCOLOR

101 interlake Blue


102 inter Red
103 clipper Green
104 Marine Red
4 rows selected.
DATABASE MANAGEMENT SYSTEMS LAB

322103310140 25
DATABASE MANAGEMENT SYSTEMS LAB

CREATE A TABLE RESERVES WHICH CONTAINS ATTRIBUTES BID, SID,


DAY AND INSERTING VALUES IN IT.

SQL> CREATE TABLE reserves


2 (sid INT,
3 bid INT,
4 day VARCHAR2(20));
Table created.
SQL> INSERT INTO reserves VALUES(22,101,'10-Oct-98');
1 row created.
SQL> INSERT INTO reserves VALUES(22,102,'10-Oct-98');
1 row created.
SQL> INSERT INTO reserves VALUES(22,103,'10-Aug-98');
1 row created.
SQL> INSERT INTO reserves VALUES(22,104,'10-Jul-98');
1 row created.
SQL> INSERT INTO reserves VALUES(31,104,'10-Dec-98');
1 row created.
SQL> INSERT INTO reserves VALUES(64,102,'10-Aug-98');
1 row created.
SQL> INSERT INTO reserves VALUES (74,103,'10-Aug-98');
1 row created.
SQL> SELECT * FROM
reserves; SID BID DAY

22 101 10-OCT-98
22 102 10-OCT-98
22 103 10-AUG-98
22 104 10-JUL-98
31 104 10-DEC-98
64 102 10-AUG-98
74 103 10-AUG-98

1) Find the name of sailors who have reserved boat number 103?
SQL> SELECT sname FROM sailors WHERE sid in (SELECT sid FROM reserves WHERE

322103310140 26
DATABASE MANAGEMENT SYSTEMS LAB

bid=103);

SNAME

dustin
Horatio

2) Find the name of sailors who have reserved a red boat?


SQL> SELECT sname FROM sailors WHERE sid in (SELECT sid FROM reserves WHERE bid IN
(SELECT bid FROM boats WHERE bcolor='red'));

SNAME

dustin
lubber
Horati
o

3) Find the name of sailors who have not reserved a red boat?
SQL> SELECT sname FROM sailors WHERE sid NOT IN (SELECT sid FROM reserves WHERE
bid IN (SELECT bid FROM boats WHERE bcolor='red'));

SNAME

brutus
andy
rusty
Horatio

4) Find the sailors whose rating is better than sailor ‘horatio’?


SQL> SELECT * FROM sailors WHERE srating> (SELECT max(srating) FROM sailors WHERE
sname='horatio');

SID SNAME SRATING SAGE

58 rusty 10 36

5) Find the sailors with highest rating?


SQL> SELECT * FROM sailors WHERE srating IN (SELECT max(srating) FROM

sailors); SID SNAME SRATING SAGE

58 rusty 10 36

6) Find the name of sailors who have reserved boat number 103 using exists?
SQL> SELECT sname FROM sailors s WHERE EXISTS(SELECT sid FROM reserves r WHERE
r.bid=103 and s.sid=r.sid);

322103310140 27
DATABASE MANAGEMENT SYSTEMS LAB

SNAME

dustin
horatio

7) Find the name of sailors who have reserved all boats?


SQL> SELECT sname FROM sailors s WHERE NOT EXISTS(SELECT b.bid FROM boats
b WHERE NOT EXISTS(SELECT r.bid FROM reserves r WHERE r.bid=b.bid and
s.sid=r.sid));

SNAME

dustin

322103310140 28
DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-7:
AIM: Queries using Joins
DESCRIPTIO
N:
JOINS:
● Combination of two or more tables based on condition with atleast one column common in
all tables.
● Types of joins:
● INNER JOIN
● LEFT JOIN
● RIGHT JOIN
● FULL JOIN
● SELF JOIN
● CROSS JOIN
● INNER JOIN:
● SYNTAX: SELECT columns
FROM table1
INNER JOIN table2 ON table1.column = table2.column;
● LEFT JOIN:
● SYNTAX: SELECT columns
FROM table1
LEFT JOIN table2 ON table1.column = table2.column;
● RIGHT JOIN:
● SYNTAX: SELECT columns
FROM table1
RIGHT JOIN table2 ON table1.column = table2.column;
● FULL JOIN:
● SYNTAX: SELECT columns
FROM table1
FULL JOIN table2 ON table1.column = table2.column;
● SELF JOIN:
● SYNTAX: SELECT columns
FROM table1
JOIN table2 ON table1.column = table2.column;
● CROSS JOIN:
● SYNTAX: SELECT columns
FROM table1
CROSS JOIN table2
PROGRAM:
SQL> CREATE TABLE student(
2 sid INT,
3 sname VARCHAR2(25),
4 scgpa INT,
5 smarks INT);

Table created.

SQL> INSERT INTO student VALUES(140,'Viswa',9,900);

322103310140 29
DATABASE MANAGEMENT SYSTEMS LAB

1 row created.

SQL> INSERT INTO student VALUES(180,'Prasad',8,864);

1 row created.

SQL> INSERT INTO student VALUES(167,'Pavan',8.5,889);

1 row created.

SQL> CREATE TABLE branch(


2 sid INT,
3 sbranch

VARCHAR2(90)); Table

created.

SQL> INSERT INTO branch VALUES(140,'CSE');

1 row created.

SQL> INSERT INTO branch VALUES(180,'IT');

1 row created.

1) INNER JOIN:
SQL> SELECT * FROM student s INNER JOIN branch b ON s.sid=b.sid;

SID SNAME SCGPA SMARKS SID SBRANCH

140 Viswa 9 900 140 CSE


180 Prasad 8 864 180 IT

2) LEFT JOIN:
SQL> SELECT * FROM student s LEFT JOIN branch b ON s.sid=b.sid;

SID SNAME SCGPA SMARKS SID SBRANCH

140 Viswa 9 900 140 CSE


180 Prasad 8 864 180 IT
167 Pavan 8.5 889 167

3) RIGHT JOIN:
SQL> SELECT * FROM student s RIGHT JOIN branch b ON s.sid=b.sid;

SID SNAME SCGPA SMARKS SID SBRANCH

322103310140 30
DATABASE MANAGEMENT SYSTEMS LAB

140 Viswa 9 900 140 CSE


180 Prasad 8 864 180 IT

4) FULL JOIN:
SQL> SELECT * FROM student s FULL JOIN branch b ON s.sid=b.sid;

SID SNAME SCGPA SMARKS SID SBRANCH

140 Viswa 9 900 140 CSE


180 Prasad 8 864 180 IT
167 Pavan 8.5 889 167

5) CROSS JOIN:
SQL> SELECT * FROM student s CROSS JOIN branch b;

SID SNAME SCGPA SMARKS SID SBRANCH

140 Viswa 9 900 140 CSE


180 Prasad 8 864 140 CSE
167 Pavan 8.5 889 140 CSE
140 Viswa 9 900 180 IT
180 Prasad 8 864 180 IT
167 Viswa 8.5 889 180 IT
6 rows selected.
6) SELF JOIN:
SQL> SELECT a.sid,b.scgpa FROM student a, student b where

a.scgpa<b.scgpa; SID SCGPA

140 8
140 8

322103310140 31
DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-8:
AIM: Queries using Views
DESCRIPTIO
N:
VIEWS:
● Views are a kind of virtual tables
● Views are logical representation of one or more tables
● SYNTAX FOR CREATING A VIEW:
CREATE VIEW view_name AS
SELECT column1, column2, ... FROM
table_name WHERE condition;
● SYNTAX FOR INSERTING VALUES INTO A VIEW:
INSERT INTO view_name VALUES (value1, value2, ...);
● SYNTAX FOR UPDATING A VIEW:
UPDATE view_name SET column = value WHERE condition;
● SYNTAX FOR DROPPING A VIEW:
DROP VIEW view_name;

PROGRAM:
CREATING A VIEW:
SQL> CREATE VIEW std AS SELECT s.sid,s.sname FROM student s WHERE s.sid>140;
View created.
SQL> SELECT * FROM std;
SID SNAME

180 Prasad
167 Pavan

INSERTING VALUES INTO A VIEW


SQL> INSERT INTO std VALUES (137,'Geeth');
1 row created.
SQL> SELECT * FROM std;
SID SNAME

180 Prasad
167 Pavan
137 Geeth

UPDATING A VIEW:
SQL> UPDATE std SET sname='Sri' WHERE
sid=137; 1 row updated
SQL> SELECT * FROM std;
SID SNAME

180 Prasad
167 Pavan
137 Sri
DROPPING A VIEW:
SQL> DROP VIEW
std;

322103310140 32
DATABASE MANAGEMENT SYSTEMS LAB

View dropped.

322103310140 33
DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-9:
AIM: Procedures and Functions.
DESCRIPTION:
A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the Modular design.
PROCEDURES:
● These are subprograms do not return a value directly.
● These are mainly used to perform an action.
● At schema level, subprograms are called as standalone procedures.
● A standalone procedure can be called in two ways −
● Using the EXECUTE keyword
EXECUTE
procedure_name;
● SYNTAX FOR CREATING A PROCEDURE:
CREATE OR REPLACE PROCEDURE
procedure_name (parameter_name [IN|OUT|INOUT]
type…..)
{AS/IS}
BEGIN
<procedure_body>
END procedure_name;
● SYNTAX FOR DROPPING A PROCEDURE:
DROP PROCEDURE procedure_name;
FUNCTIONS:
● These are subprograms return a value directly.
● These are mainly used to compute and return a value.
● SYNTAX FOR CREATING A FUNCTION:
CREATE OR REPLACE FUNCTION
function_name (parameter_name [IN|OUT|INOUT]
type…..) RETURN type;
{AS/IS}
BEGIN
<function_body>
END function_name;
● SYNTAX FOR DROPPING A FUNCTION:
DROP PROCEDURE function_name;
In syntax, CREATE allows to create a new procedure or function. REPLACE allows to modify an
existing procedure or function. There are three parameter modes in PL&SQL block. One of the
mode is IN, which is a default parameter and always receives values from calling function. Another
mode is OUT, which always sends values to the calling function. Last mode is IN OUT, which
performs both operations i.e. receives as well as sends information.

PROGRAM:
1) Write a PL&SQL code to display grades according to marks
SQL> set serveroutput on
SQL> DECLARE
2 marks number;
3 grade varchar2(90);
4 BEGIN
5 marks:=&marks;
DATABASE MANAGEMENT SYSTEMS LAB
322103310140 34
DATABASE MANAGEMENT SYSTEMS LAB

6 if marks>=90 then
7 grade:='A';
8 elsif marks>=80 then
9 grade:='B';
10 elsif marks>=70 then
11 grade:='C';
12 elsif marks>=60 then
13 grade:='D';
14 elsif marks>=40 then
15 grade:='E';
16 else
17 grade:='F';
18 end if;
19 dbms_output.put_line('Grade is '||
grade); 20 END;
21 /
Enter value for marks: 56
old 5: marks:=&marks;
new 5: marks:=56;
Grade is E

PL/SQL procedure successfully completed.

2) Write a PL&SQL block to add two numbers using procedures inside the block
SQL> set serveroutput on
SQL> DECLARE
2 a number;
3 b number;
4 c number;
5 PROCEDURE addition(x in number, y in number, z out number)
6 AS
7 BEGIN
8 z:=x+y;
9 END
addition;
10 BEGIN
11 a:=&a;
12 b:=&b;
13 addition(a,b,c);
14 dbms_output.put_line('Output is '||
c); 15 END;
16 /
Enter value for a:
5 old 11: a:=&a;
new 11: a:=5;
Enter value for b:
4 old 12: b:=&b;
new 12: b:=4;
Output is 9

PL/SQL procedure successfully completed.

322103310140 35
DATABASE MANAGEMENT SYSTEMS LAB

3)Write a PL&SQL code to multiplication of two numbers using function


outside the block?
SQL> set serveroutput on
SQL> CREATE FUNCTION multiplication(x in number, y in number)
2 RETURN number
3 AS
4 BEGIN
5 RETURN x*y;
6 END
multiplication; 7 /

Function created.

SQL>

DECLARE
2 a number;
3 b number;
4 c number;
5 BEGIN
6 a:=&a;
7 b:=&b;
8 c:=multiplication(a,b);
9 dbms_output.put_line('Output is '||
c); 10 END;
11 /
Enter value for a:
5 old 6: a:=&a;
new 6: a:=5;
Enter value for b:
4 old 7: b:=&b;
new 7: b:=4;
Output is 20

PL/SQL procedure successfully completed.

4) Write a PL&SQL code to find factorial of a given number using function


inside the block
SQL> set serveroutput on
SQL> DECLARE
2 a number;
3 b number;
4 FUNCTION factorial(x in number)
5 RETURN number
6 AS
7 res number:=1;
8 BEGIN
9 for i in 1..x
10 loop
11 res:=res*i;
12 end loop;
13 return res;
DATABASE MANAGEMENT SYSTEMS LAB
322103310140 36
DATABASE MANAGEMENT SYSTEMS LAB

14 END
factorial;
15 BEGIN
16 a:=&a;
17 b:=factorial(a);
18 dbms_output.put_line('Output is '||
b); 19 END;
20 /
Enter value for a:
5 old 16: a:=&a;
new 16: a:=5;
Output is 120

PL/SQL procedure successfully completed.

322103310140 37
DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-10:
AIM: Implicit and Explicit Cursors.
DESCRIPTIO
N:
CURSORS:
⮚ A CURSOR is nothing but a pointer between the contest area and physical data storage.
⮚ Contest area is a memory which is reserved by oracle for crossing SQL statements.
⮚ These are mainly used to perform an action.
⮚ A CURSOR can be divided into two types
● EXPLICIT CURSORS
● IMPLICIT CURSORS
⮚ EXPLICIT CURSORS:
● These are nothing but user defined cursors
● These are programmer-defined cursors for gaining more control over contest area.
● An explicit cursor should be declared inside the declaration section of
PL&SQL code.
● It is created on a SELECT statement which returns more than one row.
⮚ IMPLICIT CURSORS:
● If the oracle opened a cursor for its internal processing then it is called IMPLICIT
CURSOR.
● ATTRIBUTES OF IMPLICIT CURSORS ARE:
1. SQL%found
2. SQL%notfound
3. SQL%rowcount
4. SQL%type
5. SQL%rowtype
● SQL%found: It returns true if the operation is successful. Otherwise, false.
● SQL%notfound: It returns false if the operation is successful. Otherwise, true.
● SQL%rowcount: It returns number of rows fetched by cursor.
● SQL%type: It is useful when you want create a variable with same type.
● SQL%rowtype: It is used to declare a record variable.
⮚ ACTION OF CURSORS:
● DECLARING A CURSOR:
CURSOR cursor_name IS SQL SELECT statement;
● OPENING A CURSOR:
OPEN cursor_name;
● FETCHING A RECORD FROM CURSOR:
FETCH cursor_name INTO variables,….;
● CLOSING A CURSOR:
CLOSE cursor_name;

PROGRAM:
1) Write a PL&SQL block to display the name of the students belonging to
CSE branch using CURSORS.
SQL> CREATE TABLE student(
2 sid INT,
3 sname VARCHAR2(25),
4 scgpa INT,

322103310140 38
DATABASE MANAGEMENT SYSTEMS LAB

5 smarks INT
6 sbranch

VARCHAR2(90)); Table

created.

SQL> INSERT INTO student VALUES(140,'Viswa',9,900,’CSM’);

1 row created.

SQL> INSERT INTO student VALUES(180,'Prasad',8,864,’CSD’);

1 row created.

SQL> INSERT INTO student VALUES(167,'Pavan',8.5,889,’CSE’);

1 row created.

SQL> SELECT * FROM student;

SID SNAME SCGPA SMARKS SBRANCH

140 Viswa 9 900 CSM


180 Prasad 8 864 CSD
167 Pavan 8.5 889 CSE

SQL> set serveroutput on


SQL> DECLARE
2 name student.sname%type;
3 CURSOR c IS SELECT sname FROM student WHERE SBRANCH=’CSE’;
4 BEGIN
5 OPEN C;
6 LOOP
7 FETCH c INTO name;
8 EXIT WHEN c%notfound;
9 dbms_output.put_line(name);
10 END LOOP;
11 CLOSE c;
12 END;
13 /
Pavan

PL/SQL procedure successfully completed.

2) Write a PL&SQL block to increase salary of all engineers by 1000.


SQL> CREATE TABLE engineer
2 (id INT,
3 name VARCHAR2(90),
4 salary INT);

322103310140 39
DATABASE MANAGEMENT SYSTEMS LAB

Table created.

322103310140 40
DATABASE MANAGEMENT SYSTEMS LAB

SQL> INSERT INTO engineer VALUES(167,'Pavan',10000);

1 row created.

SQL> INSERT INTO engineer VALUES(125,'Sri',12000);

1 row created.

SQL> INSERT INTO engineer VALUES(199,'Vardhan',15000);

1 row created.

SQL> SELECT * FROM


engineer; ID NAME SALARY

167 Pavan 10000


127 Sri 12000
199 Shyam 15000

SQL> DECLARE
2 s engineer.salary%type;
3 CURSOR a IS SELECT salary FROM engineer FOR UPDATE;
4 BEGIN
5 OPEN a;
6 LOOP
7 FETCH a INTO s;
8 EXIT WHEN a%notfound;
9 UPDATE engineer SET salary=s+1000 WHERE CURRENT OF a;
10 END LOOP;
11 CLOSE a;
12 END;
13 /

PL/SQL procedure successfully completed.

SQL> SELECT * FROM engineer;

ID NAME SALARY

167 Pavan 11000


125 Sri 13000
199 Shyam 16000

322103310140 41
DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-11:
AIM: Triggers
DESCRIPTI
O N:
TRIGGERS:
● A trigger is a stored procedure in database which automatically invokes whenever
a special event in the database occurs.
● When an event occurs, Trigger is fired and an predefined PL&SQL block
will perfom necessary action
● Triggers has 3 parts
● Trigger Event
● Condition
● Trigger Action
● SYNTAX FOR CREATING A TRIGGER:
CREATE OR REPLACE TRIGGER
trigger_name BEFORE/AFTER
DELETE/INSERT/UPDATE OF column_name
ON table_name
REFERENCING OLD AS old, NEW as new
FOR EACH ROW
WHEN CONDITION
DECLARE
<variable and constant declarations>
BEGIN
<statements>
END;
● SYNTAX FOR DISABLING/ ENABLING A TRIGGER:
ALTER TRIGGER trigger_name DISABLE/ENABLE;
● SYNTAX FOR DISABLING ALL TRIGGER:
ALTER TABLE table_name DISABLE ALL TRIGGERS;
● SYNTAX FOR DROPPING A TRIGGER:
DROP TRIGGER trigger_name;
● EXPLAINIG SYNTAX OF CREATING A TRIGGER:
● create trigger [trigger_name]: Creates or replaces an existing trigger with
the trigger_name.
● [before | after]: This specifies when the trigger will be executed.
● {insert | update | delete}: This specifies the DML operation.
● on [table_name]: This specifies the name of the table associated with the trigger.
● [for each row]: This specifies a row-level trigger, i.e., the trigger will be
executed for each row being
● affected.
● [trigger_body]: This provides the operation to be performed as trigger is fired
● BEFORE and AFTER of Trigger:
● BEFORE triggers run the trigger action before the triggering statement is run.
● AFTER triggers run the trigger action after the triggering statement is run.
● USES OF TRIGGER:
1. Prevents improper transactions
2. Accumulates information on table usage.
3. Monitor critical information

322103310140 42
DATABASE MANAGEMENT SYSTEMS LAB

PROGRAMS:
1) Write a program to create a trigger which will convert the name of student to
upper case before inserting or updating the name column of student table.
SQL> CREATE TABLE student(
2 sid INT,
3 sname VARCHAR2(25),
4 scgpa INT,
5 smarks INT
6 sbranch

VARCHAR2(90)); Table

created.

SQL> INSERT INTO student VALUES(140,'Viswa',9,900,’CSM’);

1 row created.

SQL> INSERT INTO student VALUES(180,'Prasad',8,864,’CSD’);

1 row created.

SQL> INSERT INTO student VALUES(167,'Pavan',8.5,889,’CSE’);

1 row created.

SQL> SELECT * FROM student;

SID SNAME SCGPA SMARKS SBRANCH

140 Viswa 9 900 CSM


180 Prasad 8 864 CSD
167 Pavan 8.5 889 CSE

SQL> CREATE TRIGGER t


2 BEFORE INSERT or UPDATE ON student
3 FOR EACH ROW
4 BEGIN
5 :NEW.sname:=UPPER(:NEW.sname);
6 END;
7/

Trigger created.
SQL> INSERT INTO student VALUES(147,'Shyam',9,989,'');

1 row created.
SQL> SELECT * FROM student;

SID SNAME SCGPA SMARKS SBRANCH

140 Viswa 9 900 CSM

322103310140 43
DATABASE MANAGEMENT SYSTEMS LAB

180 Prasad 8 864 CSD

322103310140 44
DATABASE MANAGEMENT SYSTEMS LAB

167 Pavan 8.5 889 CSE


147 Shyam 9 989
2) Writea program to create a trigger which will delete the details of student
from student table where a particular branch is deleted from branch table.
SQL> SELECT * FROM student;

SID SNAME SCGPA SMARKS SBRANCH

140 Viswa 9 900 CSM


180 Prasad 8 864 CSD
167 Pavan 8.5 889 CSE
147 Shyam 9 989

SQL> CREATE TABLE branch(bran VARCHAR2(89));


Table created.

SQL> INSERT INTO branch VALUES('CSE');


1 row created.

SQL> INSERT INTO branch VALUES('CSM');


1 row created.

SQL> INSERT INTO branch VALUES('CSD');


1 row created.

SQL> SELECT * FROM branch;


BRAN

CSE
CS
M
CSD
SQL> CREATE TRIGGER t1
2 BEFORE DELETE ON branch
3 FOR EACH ROW
4 BEGIN
5 DELETE FROM STUDENT WHERE sbranch=:OLD.bran;
6 END;
7/
Trigger created.

SQL> DELETE FROM student WHERE sbranch='CSM';


1 row deleted

SQL> SELECT * FROM student;


SID SNAME SCGPA SMARKS SBRANCH

180 Prasad 8 864 CSD


167 Pavan 8.5 889 CSE
147 Shyam 9 989

322103310140 45
DATABASE MANAGEMENT SYSTEMS LAB

EXPERIMENT-12:
AIM: Exception Handling
DESCRIPTIO
N:
EXCEPTION:
● It is an error which disrupts the normal flow of program instructions.
● PL&SQL provides us the exception block which raises an exception thus helping
the programmer to find out fault and resolve it.
● There are two types of Exceptions
● System Defined Exceptions
● User Defined Exceptions
● User defined exception: This type of users can create their own exceptions according to
the need and to raise these exceptions explicitly raise command is used.
● System defined exceptions: These exceptions are predefined in PL/SQL which get
raised WHEN certain database rule is violated.
● System-defined exceptions are further divided into two categories:
1. Named system exceptions.
2. Unnamed system exceptions.
● SYNTAX FOR
EXCEPTIONS: DECLARE
declarations section;
BEGIN
executable command(s);
EXCEPTION
WHEN exception1 THEN
statement1;
WHEN exception2 THEN
statement2;
[WHEN others THEN]
/* default exception handling code */
END;
● SOME EXCEPTIONS:
● NO_DATA_FOUND: It is raised WHEN a SELECT INTO statement
returns no rows.
● TOO_MANY_ROWS: It is raised WHEN a SELECT INTO statement
returns more than one row.
● VALUE_ERROR: This error is raised WHEN a statement is executed that
resulted in an arithmetic, numeric, string, conversion, or constraint error. This
error mainly results from programmer error or invalid data input.
● ZERO_DIVIDE: It raises exception WHEN dividing with zero.

PROGRAMS:
1) Write a PL&SQL block to retrieve student id using default exception
SQL> SELECT * FROM student;
SID SNAME SCGPA SMARKS SBRANCH

180 Prasad 8 864 CSD


167 Pavan 8.5 889 CSE
147 Shyam 9 989
SQL> DECLARE

322103310140 46
DATABASE MANAGEMENT

2 id student.sid%type;
3 BEGIN
4 SELECT sid INTO id FROM student;
5 EXCEPTION
6 WHEN NO_DATA_FOUND then
7 dbms_output.put_line('Table is empty');
8 WHEN TOO_MANY_ROWS then
9 dbms_output.put_line('More than one row is
selected'); 10 END;
11 /
More than one row is selected

PL/SQL procedure successfully completed.


2) Write a PL&SQL block to retrieve student name using user
defined exception SQL> SELECT * FROM student;
SID SNAME SCGPA SMARKS SBRANCH

180 Prasad 8 864 CSD


167 Pavan 8.5 889 CSE
147 Shyam 9 989
SQL> DECLARE
2 name student.sname%type;
3 NullException EXCEPTION;
4 BEGIN
5 SELECT sname INTO name FROM student WHERE sid=47;
6 if name IS NULL THEN
7 RAISE NullException;
8 else
9 dbms_output.put_line(name);
10 end if;
11 EXCEPTION
12 WHEN NO_DATA_FOUND then
13 dbms_output.put_line('Table is empty');
14 WHEN TOO_MANY_ROWS then
15 dbms_output.put_line('More than one row is selected');
16 WHEN NullException then
17 dbms_output.put_line('Found
nothing'); 18 END;
19 /
Shyam

PL/SQL procedure successfully completed.

322103310140 47

You might also like