Dbms
Dbms
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
Table created.
1 row created.
1 row created.
1 row created.
322103310140 2
DATABASE MANAGEMENT SYSTEMS LAB
Table altered.
Table altered.
Table altered.
1 row updated.
RENAMING A TABLE:
SQL> RENAME Employee to Emp;
Table renamed.
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.
1 row created.
1 row created.
sid=22;
1 row updated.
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.
29 brutus 1 33
31 lubber 8 56
2rows selected.
SNAME
lubber
Commit
complete.
values(40,'pavan',11,64);
1 row created.
SQL> savepoint a;
Savepoint created.
1 row created.
SQL> SELECT * FROM sailors;
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.
29 brutus 1 33
31 lubber 8 56
40 pavan 11 64
3 rows selected.
SQL> rollback;
Rollback complete.
SQL> SELECT * FROM sailors;
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
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
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:
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
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
Table
created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
322103310140 16
DATABASE MANAGEMENT SYSTEMS LAB
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.
VARCHAR2(9)); Table
created.
1 row created.
1 row created.
4 rows selected.
DATABASE MANAGEMENT SYSTEMS LAB
322103310140 17
DATABASE MANAGEMENT SYSTEMS LAB
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
SAGE
58 Rusty 10 36
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
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<>r2.bid and r1.sid =r2.sid and r1.day=r2.day and r1.sid=s1.sid;
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.
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.
1 DELL 50000 24
2 HP 49000 22
3 LENOVA 45000 30
4 LENOVA 46000 15
1) SUM():
91
2) COUNT():
3) AVG():
47500
4) MAX():
50000
5) MIN():
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
Table
created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
322103310140 24
DATABASE MANAGEMENT SYSTEMS LAB
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.
VARCHAR2(9)); Table
created.
1 row created.
1 row created.
322103310140 25
DATABASE MANAGEMENT SYSTEMS LAB
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
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
58 rusty 10 36
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
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.
322103310140 29
DATABASE MANAGEMENT SYSTEMS LAB
1 row created.
1 row created.
1 row created.
VARCHAR2(90)); Table
created.
1 row created.
1 row created.
1) INNER JOIN:
SQL> SELECT * FROM student s INNER JOIN branch b ON s.sid=b.sid;
2) LEFT JOIN:
SQL> SELECT * FROM student s LEFT JOIN branch b ON s.sid=b.sid;
3) RIGHT JOIN:
SQL> SELECT * FROM student s RIGHT JOIN branch b ON s.sid=b.sid;
322103310140 30
DATABASE MANAGEMENT SYSTEMS LAB
4) FULL JOIN:
SQL> SELECT * FROM student s FULL JOIN branch b ON s.sid=b.sid;
5) CROSS JOIN:
SQL> SELECT * FROM student s CROSS JOIN branch b;
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
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
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
322103310140 35
DATABASE MANAGEMENT SYSTEMS LAB
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
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
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.
1 row created.
1 row created.
1 row created.
322103310140 39
DATABASE MANAGEMENT SYSTEMS LAB
Table created.
322103310140 40
DATABASE MANAGEMENT SYSTEMS LAB
1 row created.
1 row created.
1 row created.
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 /
ID NAME SALARY
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.
1 row created.
1 row created.
1 row created.
Trigger created.
SQL> INSERT INTO student VALUES(147,'Shyam',9,989,'');
1 row created.
SQL> SELECT * FROM student;
322103310140 43
DATABASE MANAGEMENT SYSTEMS LAB
322103310140 44
DATABASE MANAGEMENT SYSTEMS LAB
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.
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
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
322103310140 47