Dbms Laboratory Manual(r23-Aiml)
Dbms Laboratory Manual(r23-Aiml)
II-II
LABORATORY MANUAL
1. To facilitate the graduates with the ability to visualize, gather information, articulate,
analyze, solve complex problems, and make decisions. These are essential to address the
challenges of complex and computation intensive problems increasing their productivity.
2. To facilitate the graduates with the technical skills that prepare them for immediate
employment and pursue certification providing a deeper understanding of the technology in
advanced areas of computer science and related fields, thus encouraging to pursue higher
education and research based on their interest.
3. To facilitate the graduates with the soft skills that include fulfilling the mission, setting
goals, showing self-confidence by communicating effectively, having a positive attitude, get
involved in team-work, being a leader, managing their career and their life.
4. To facilitate the graduates with the knowledge of professional and ethical responsibilities by
paying attention to grooming, being conservative with style, following dress codes, safety
codes, and adapting themselves to technological advancements.
EXPERIMENT 1
AIM: Queries for Creating, Dropping, and Altering Tables and insert row into a table(use constraints
while creating tables) examples using Select Command.
Procedure:
1. Creation of emp&dept table inSql:
SQL>create table dept10(deptno number(2,0) primary key,dname varchar(18) NOT NULL,loc
varchar(20) NOT NULL);
Table created.
SQL>create table emp(
empno number(4,0),
ename
varchar2(10)NOTNULL,
job varchar2(9) NOT NULL,
mgr number(4,0),
hiredate date,
sal number(7,2)NOTNULL,
commnumber(7,2),
eptno number(2,0),
constraint pk_emp primarykey(empno),
constraint fk_deptno foreignkey(deptno) references dept (deptno)
);
Table created.
2. View Structure/schema of emp&dept table in
sql: SQL> select *from emp;
No rows selected
SQL>select*from dept;
No rows selected
SQL>desc emp;
Name Null? Type
SQL>/
Enter value for deptno:20
Enter value for dname: admin
Enter value for loc:hyd
old1: insert into dept values(&deptno,'&dname','&loc')
1 row created.
SQL>/
Enter value for deptno: 30
Enter value for dname: marketing
Enter value for loc: vzg
old1: insert into dept values (&deptno,'&dname','&loc')
new1: insert into dept values (30,'marketing','vzg')
1 row created.
4. Select Command: this command is used to print there cord from the existing table. View all
records in dept table:
SQL>select*from dept;
DEPTNO DNAME LOC
10 sales Vijayawada
20 admin hyd
30 marketing vzg
-----------------------------------------------------------------
10 sales Vijayawada
Types of SQL Commands:
DDL: DDLCommands(DataDefinition Language)
1. CREATE 2.DESC 3.ALTER 4.DROP 5.TRUNCATE 6.RENAME
DML Commands (DataManipulationLanguage)
1. SELECT 2. INSERT 3.UPDATE 4.DELETE
TCL (Transaction Control Language)
1. COMMIT 2.ROLLBACK 3.SAVEPOINT
DCL Commands(Data Control Language)
1. GRANT 2.REVOKE
1. CREATE:
CREATE TABLE: This is used to create a new relation and the corresponding
Syntax: CREATE TABLE relation_name(field_1data_type(Size),field_2data_type(Size),...);
Example:
SQL>CREATE TABLE Student (id number, namevarchar2 (10));
EXPERIMENT:2
SQL>SELECT*FROM EMPLOYEE;
FNAME LNAME SSNBDATE ADDRESS G SALARY SUPER_SSN DNO
1111 SMITH M
2222 POOJA F
3333 MARTIN M
3333 RAJA M
1. ALL
Retrieve the names of employees whose salary is greater than the salary of all the employees in
department 10
SQL>SELECT FNAME,LNAME FROM EMPLOYEE WHERE SALARY > ALL(SELECT
SALARY FROM EMPLOYEE WHERE DNO=10);
FNAME LNAME
ALLEN
MARTIN
TURNER
2. ANY
TURNER
MARTIN ALLEN
BLAKE
SMITH
3. IN
Retrieve the name of each employee who has a dependent with the first name and same gender as the
employee
SQL>SELECT e.FNAME, e.LNAME FROM EMPLOYEE e WHERE e.SSNIN(SELECT ESSN
FROM DEPENDENT WHERE e.GENDER=GENDER AND e.FNAME =
DEPENDENT_NAME);
FNAME LNAME
SMITH
MARTI
N
4. EXISTS
Retrieve the name of each employee who has a dependent with the firstname and same gender as the
employee
SQL>SELECT e.FNAME,e.LNAME FROM EMPLOYEE e WHERE EXISTS (SELECT
* FROM DEPENDENT WHERE e.SSN=ESSN AND e.GENDER=GENDER AND
e.FNAME =DEPENDENT_NAME);
FNAME LNAME
SMITH
MARTI
N
5.NOTEXISTS
Retrieve the names of employees who have no dependents
SQL>SELECT FNAME,LNAME FROM EMPLOYEE WHERE NOTEXISTS(SELECT*
ALLEN
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can be inserting into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the constraint and the
data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table
level constraints apply to the whole table.
The following constraints are commonly used in SQL:
NOTNULL-Ensures that a column cannot have a NULL value
Example:
SQL>create table person1(idint,namevarchar2(10)not null,age int);
Table created.
UNIQUE-Ensures that all values in a column are different
Example:
SQL>create table person(id intunique,namevarchar2(10),age int);
Table created.
PRIMARYKEY-A combination of a NOTNULL and UNIQUE. Uniquely identifies each
row in a table
Example:
SQL>create table emp1(id number(10)primarykey,namevarchar2(10),sal int); Table
created.
FOREIGNKEY-Uniquely identifies a row/record in another table
oA FOREIGNKEY is a key used to link two tables together.
oA FOREIGNKEY is a field(or)collection of fields in one table that refers to the
PRIMARY KEY in another table.
o The table containing the foreign key is called the child table, and the table containing
the candidate key is called the referenced or parent table.
Example:
SQL>create table emp2(eidint,cityvarchar2(10),foreign key(eid)referencesemp1(id));
Table created.
CHECK-Ensures that all values in a column satisfies a specific condition
Example:
SQL>CREATE TABLE person1( ID int ,Age int, City varchar(10),CONSTRAINT chk
CHECK(Age>=18 AND City='vja');
Table created.
NO_EMP
--------------
5
2. SUM: Calculate the total salaries for each dept
SQL>SELECT DEPTNO, SUM (SAL) FROM EMP GROUPBY DEPTNO;
------------------------
30 9400
20 10875
10 8750
DEPT_ NOAVG(SAL)
---------- ----------
30 1566.66667
20 2175
10 2916.66667
DEPTNO MAX(SAL)
-------------------------
30 2850
20 3000
10 5000
5. MIN
Calculate the minimum salary for each dept
30 950
20 800
10 1300
6. GROUPBY:
The GROUP BY clause is a SQL command that is used to group rows that have the same values.
The GROUPBY clause is used in the SELECT statement. Optionally it is used in conjunction with
aggregate functions to produce summary reports from the database.
GROUPBY Syntax
SELECT statements…GROUPBYcolumn_name1[column_name2,…];
Grouping using a Single Column:
Create a table called data with gender column and values as male and female.
SQL>select *from data;
GENDER
male
female
female
female
female
female
male male
male
female
male male
female
male male
female
16 rows selected.
SQL>select gender from data GROUPBY gender;
GENDER
------------
Male
Female
SQL>select count(gender), gender from data GROUPBY gender;
COUNT(GENDER) GENDER
8 male
8 female
Grouping using Multiple
COMPUTER SCIENCE & ENGINEERING Page 17
DATABASE MANAGEMENT
II-II
Columns Syntax
SELECT Column1,Column2,AGGREGATE_FUNCTION(Column3) FROM TABLE1 GROUPBY
Column1,Column2;
Examples:
SQL>select *from emp;
ID NAME
3 c
4 d
1 a
2 b
5 a
1 z
6 e
7 rows selected.
7. HAVING
The HAVING clause was added to SQL because the WHERE keyword could not be used with
Aggregate functions.
The WHERE clause places conditions on the selected columns, where as the HAVING
clause places conditions on groups created by the GROUP BY clause.
The HAVING clause must follow the GROUPBY clause in a query and must also
precede the ORDER BY clause if used
HAVING Syntax
SELECT column_name(s) FROM table_name WHERE condition GROUPBY
column_name(s) HAVING condition
SQL>select *from emp;
ID NAME DEPT SAL
1 a cse 1000
ERRORatline1:
ORA-00942: table or view does not exist
EXPERIMENT:4
$15000.00
$20000.00
$42000.00
$23000.00
$50000.00
1210.73
3. to_date: to_date is used for convert and display the attribute values as
date. SQL> select to_date('01-01-2020', 'MM-DD-YYYY') from dual;
TO_DATE('
01-JAN-20
b) String functions:
1. Concatenation:CONCAT is used to add two attribute values such as string.
SQL>select concat(eno,loc) from emp;
CONCAT(ENO,LOC)
101 vja
102 hyd
103 vja
COMPUTER SCIENCE & ENGINEERING Page 22
DATABASE MANAGEMENT
II-II
104 gnt
106 hyd
2lpad: LPAD()function is used top adding the left side of a string with a specific set of characters.
SQL>select lpad(ename,10,'*') from emp;
LPAD(ENAME,10,'*')
*******ali
******haji
**mohammad
******ravi
****irfath
3rpad: RPAD() function is used top adding the right side of a string with a specific set of characters.
SQL>select rpad(ename,10,'*') from emp;
RPAD(ENAME,10,'*')
ali*******
haji******
mohammad**
ravi******
irfath****
4.ltrim:LTRIM() function is used to remove all specified characters from the left end side of a string
SQL>select ltrim('******hi********','*')fromdual;
LTRIM('*** hi********
5. rtrim:RTRIM() function is used to remove all specified characters from the left end side of a
string
SQL>select rtrim('******hi********','*')from dual;
RTRIM('******hi********','*')
******hi
6. lower: lower() function is used to convert the attribute value into lowercase.
SQL>select lower(ename) from emp;
LOWER(ENAME)
a
l
h
a
j
i
mo
ham
mad
ravi
irfath
7. upper:upper() function is used to convert the attribute values into uppercase.
SQL>select upper(ename) from emp;
UPPER(ENAME)
ALI
HAJI
MOHA
MMAD
RAVI
IRFATH
7. initcap:initcap() is used to convert the attribute values first character in capital letter.
SQL>select initcap(ename) from emp;
INITCAP(EN
A
l
i
H
a
j
i
Mo
ham
mad
Ravi
Irfath
9. length:length() function is used to calculate the length of the given attribute.
SQL>select ename,length(ename) from emp;
ENAME LENGTH(ENAME)
10. substr:substr() function is used to find the substring of the given attribute value. It returns
size-1 of the given string/ attribute as a sub string.
SQL>selecte name,substr(ename,4) from emp;
ENAME SUBSTR(ENAME,4)
ali
haji i
mohammad
ammad ravi i
irfath ath
11. instr:instr() function return the location of starting passion of the substring in the existing
value.
SQL>select instr('welcometoCRRCOE','to') from dual;
INSTR('WELCOMETO
CRRCOE','TO') 9
c) Date functions:
1. Sysdate():sysdate() function returns the current system date.
SQL>select sysdate from dual;
SYSDATE
28-APR-21
2. next_day();it reurns the date of next coming day.
SQL>select next_day(sysdate,'sunday') from dual;
NEXT_DAY( 02-MAY-
21
3. add_months():it returns the next date after adding number of months in the arguments.
SQL>select add_months(sysdate,5)from dual;
ADD_MONTH
28-SEP-21
COMPUTER SCIENCE & ENGINEERING Page 25
DATABASE MANAGEMENT
II-II
4. last_day(): The LAST_DAY()function takes a date value as argument and returns the last
day of month in that date
SQL>select last_day(sysdate) from dual;
LAST_DAY( 30-APR-21
29-FEB-20
MONTHS_BETWEEN(SYSDATE,'02-FEB-2020')
14.8600769
6. least():it returns least value from the given argument or attributes.
SQL>select least(300,450,100,440)from dual;
LEAST(300,450,100,
440) 100
7. greatest():it returns maximum values from the given arguments or attributes in the relation.
SQL>select greatest(300,450,100,440)from dual;
GREATEST(300,450,100,
440) 450
8. trunc():The TRUNC() function returns a DATE value truncated to a specified unit.
SQL>select trunc(sysdate,'mm') from dual;
TRUNC(SYS 01-APR-21
ROUND(12.49,0) 12
10. to_char():it convert the given date type attribute values to text and return the date in the
specific format.
SQL>select to_char(sysdate,'yyyy-mm-dd')from dual;
TO_CHAR(SY
2021-04-28
EXPERIMENT:5
AIM i)Create a simple PL/SQL program which includes declaration section, executable section and
29
exception –Handling section (Ex. Student marks can be selected from the table and printed for those
whose 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 PL/SQL block..
i).We have to create the student table and insert the records into the table as
follows: SQL> create table student(sid number(10),sname varchar2(20),rank
varchar(10));
Table created.
SQL>insert into student values(501,'Ravi','second');
1 row created.
SQL>insert into student values(502,'Raju','third');
1 row created
SQL>insert into student values(503,'Ramu','');
1 row created.
SQL>select*from student;
SIDSNAME RANK
501Ravi second
502Raju third
503Ramu
SQL>ed5a
Enter the following code into the text editor and save the file with .sql format
Set serveroutput on;
declare
temp1 number(10);
temp2 varchar2(10);
begin
select sid,sname into temp1,temp2 from student where rank='first';
dbms_output.put_line('StudentNo:'||temp1||'Name:'||temp2||'gotfirst rank');
exception
when no_data_found then
dbms_output.put_line('********************************************);
dbms_output.put_line('# Error: there is no student got first
rank');
end;
/
SQL>@5a;
COMPUTER SCIENCE & ENGINEERING Page 28
DATABASE MANAGEMENT
II-II
********************************************
# Error: there is no student got first rank
PL/SQL procedure successfully completed.
SQL>update student set rank='first' where sid=503;
1 row updated.
SQL>select*from student;
SIDSNAME RANK
501Ravi second
502Raju third
503Ramu first
SQL>@5a
StudentNo: 503Name:Ramu got first rank
PL/SQL procedure successfully completed.
ii) Insert data into student table and use COMMIT,ROLLBACK and SAVEPOINT in PL/SQL block
SQL>select*from student;
PL/SQLCODE:
SQL>ed5b
Enter the following code into the text editor and save the file with .sql format
set serveroutput on;
DECLARE
sno student.sid%type;
names tudent.sname%type;
srank student.rank%type;
BEGIN
sno := &sno;
name:='&name';
srank:='&srank';
INSERTinto student values(sno,name,srank);
dbms_output.put_line('One record inserted');
COMMIT;
--adding savepoint
EXPERIMENT:6
AIM: Develop a program that includes the features NESTED IF,CASE and CASE expression. The program
Can be extended using the NULLIF and COALESCE functions
A.NESTED IF:
A nested if-then is an if statement that is the target of another if statement. Nested if-then
statements mean an if statement inside another if statement
Syntax:-
if(condition1)then
-- Executes when condition1 is true
if (condition2) then
-- Executes when condition2 is true
end if;
end if;
PL/SQL CODE:PL/SQL Program to find biggest of three number using nested if.
SQL>ed 6a
Enter the following code into the text editor and save the file with .sql format
declare
a number:=10;
b number:=12;
c number:=5;
begin
dbms_output.put_line('a='||a||'b='||b||'c='||c); if a>b AND a>c
then
dbms_output.put_line('a is greatest');
else
if b>a AND b>ct hen
dbms_output.put_line('b is greatest');
else
dbms_output.put_line('c is greatest');
endif;
endif;
end;
/
SQL>@6a
a=10 b=12 c=5
B. CASE and CASE Expression: CASE statement selects one sequence of statements to execute.
However, to select the sequence, the CASE statement uses a select or rather han multiple Boolean
expressions. A selector is an expression, the value of which is used to select one of several alternatives.
Syntax
CASEselector
WHEN 'value1' THEN S1;
--defaultcase
END CASE;
SQL>create table emp(enonumber(5),enamevarchar2(10),locvarchar(10),salary number(10,2));
Table created.
SQL>insert into emp values(101,'ali','vja',15000);
1 row created.
SQL>insert into emp values(102,'ravi','hyd',25000);
1 row created.
SQL>insert into emp values(103,'raju','gnt',35000););
1 row created.
SQL>insert into emp values(104,'rakesh','vja',45000);
1 row created.
SQL>select * from emp;
ENO ENAME LOC SALARY
LOC rev_salary
vja 17000
hyd 26000
gnt 35000
vja 47000
SQL> ed 6b
Syntax: coalesce("expression1","expression2",...);
Example:
SQL>select coalesce(NULL,'CRRCOE','IT') from dual;
COALE
CRRCOE
AIM: Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT–IN Exceptions, USE defined Exceptions, RAISE APPLICATION
ERROR
PROCEDURE:
A. WHILE LOOP: AWHILE LOOP statement in PL/SQL programming language repeatedly
executes a target statement as long as a given condition is true.
Syntax:
WHILE condition LOOP
sequence_of_statements
END LOOP;
PL/SQL Code:A PL/SQL Program to find sum of ODD number up to given number using While loop
SQL> ed 7a
set serveroutput on;
declare
inval number;
endval number;
snumber default0;
begin
inval:=1;
endval:=&endval;
while inval<endvalloop
s:=s+inval;
inval:=inval+2;
endloop;
dbms_output.put_line('sumofoddnumbersbetween1and '||endval||'is'||s); end;
/
SQL>@7a
Enter value for endval: 100
old7:endval:=&endval;
new7:endval:=100;
sum of odd numbers between 1 and 100 is 2500
PL/SQL procedure successfully completed.
FOR Loop: A FORLOOP is a repetition control structure that allows us to efficiently write a loop
that needs to execute a specific number of times.
Syntax
FOR counter IN initial_value..final_value LOOP
sequence_of_statements;
EXPERIMENT:8
AIM: Programs development using creation of procedures, passing parameters IN and OUT of PROCEDURES
PROCEDURES:
SQL>create table enquiry(enqno1number(3),fname varchar2(30));
Table created.
SQL>insert into enquiry values(111,'sai');
1 row created.
SQL>insert into enquiry values(112,'sindhu');
1 row created.
end;
/
SQL>@findname Procedure created.
PL/SQL Code for calling procedure in program
SQL>ed pro8
Set serveroutput on;
declare
enqno2 number(5);
fname2varchar2(30);
begin
enqno2:=&enqno2;
findname(enqno2,fname2);
dbms_output.put_line('Person name of equiryid'||enqno2||'is'||fname2);
end;
/
SQL>@pro8
Enter value for enqno2:114
old5: enqno2:=&enqno2;
SQL>@pro8
Enter value for enqno2:112
old5: enqno2:=&enqno2;
new5:enqno2:=112;
Person name of equiry id 112 is sindhu
PL/SQL procedure successfully completed.
AIM: Program development using creation of stored functions, invoke functions in SQL statements and
write Complex functions.
PROCEDIRE:
SQL>create table dept(deptno int,dname varchar(10));
Table created.
SQL>insert into dept values(1219,'sai');
1 row created.
end;
/
SQL>@getname
Function created.
PL/SQL Code for calling function in program
SQL>ed pro9
SQL>@pro9
Enter value for deptno:1219
old5: deptno2:=&deptno;
new5:deptno2:=1219;
sai is in deptno 1219
PL/SQL procedure successfully completed.
SQL> @pro9
Enter value for deptno:1001
old5: deptno2:=&deptno;
new5:deptno2:=100;
declare
*
ERRORatline1:
ORA-20100:Your entered Department number is not exists
4 rows selected.
The following program will update the table and increase the salary of each customer by 500 and use
the SQL%ROWCOUNT attribute to determine the number of rows affected
DECLARE
total_rows number(2);
6 customers selected
PL/SQL procedure successfully completed.
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Output
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
EXPERIMENT:11
AIM: Develop programs using before and after triggers, row and statement triggers and instead of triggers
PROCEDURE:
SQL>create table customers(id number(3),name varchar2(10),age number(3),address varchar2(10),salary
number(10,2));
Table created.
SQL>insert into customers values(1,'ramesh',32,'ahmedabad',2000);
1 row created.
SQL>insert into customers values(2,'khilan',25,'Delhi',1500);
1 row created.
SQL>insert into customers values(3,'kaushik',23,'Kota',2000);
1 row created.
SQL>insert into customers values(4,'chitali',25,'Mumbai',6500);
1 row created.
SQL>select*from customers;
IDNAME AGEADDRESS SALARY
-
1 ramesh 32ahmedabad 2000
2 khilan 25 Delhi 1500
3 kaushik 23 Kota 2000
4 chitali 25Mumbai 6500
4 rows selected.
PL/SQL Code for creation of trigger while insert /update records into a table.
SQL>ed pro11
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN(NEW.ID>0)
DECLARE
sal_diff
number; BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: '||:NEW.salary);
dbms_output.put_line('Salary difference:'||sal_diff);
END;
/
AIM: Create a table and perform the search operation on table using indexing and non-indexing techniques
PROCEDURE:
SQL>CREATE TABLE TEACHER(STAFF_IDVARCHAR2(4)PRIMARY KEY,STAFF_NAME
VARCHAR2(30),QUALIFICATION VARCHAR2(10),HIREDATE DATE,JOB VARCHAR2(30),
ADDRESS VARCHAR2(15),PH_NUM NUMBER(10),SALARY NUMBER(7,2),DEPARTMENT
VARCHAR2(10));
Table created.
SQL>insert into teacher values('T101','SUNITHA','MCA','29-JUN-06','ASSOCIATE
PROFESSOR','VIJAYAWADA',9985061308,23000,'MCA');
1 row created.
SQL>insert into teacher values('T102','FREDSMITH','MTECH','07-MAR-03','ASSOCIATE
PROFESSOR','GUNTUR',9985063445,36000,'MBA');
1 row created.
07','PROFESSOR','TENALI',9985012345,27000,'MTECH');
1 row created.
PROFESSOR','VIJAYAWADA',9985045678,29000,'BTECH');
1 row created.
PROFESSOR','ELURU',9987651308,36000,'MCA');
1 row created.
03','PROFESSOR','HYDERABAD',8876561308,46000,'MCA');
1 row created.
SQL>insert into teacher values('T107','JOHNDOE','MSC(PHY)','06-FEB-04','ASSISTANT
PROFESSOR','VIJAYAWADA',8345661308,31000,'MBA');
1 row created
SQL>insert into teacher values('T108','KIMSMITH','MCA','10-MAR-08','ASSISTANT
COMPUTER SCIENCE & ENGINEERING Page 48
DATABASE MANAGEMENT
II-II
PROFESSOR','VIZAG',8374561308,26000,'MTECH');
1 row created.