36
DATABASE MANAGEMENT SYSTEMS LAB (A0595104) LAB MANUAL RGM R-19 Regulations Department of Computer Science and Engineering Rajeev Gandhi Memorial College of Engineering and Technology (Autonomous) Nandyal, Kurnool Dist. A.P.

Rajeev Gandhi Memorial College of Engineering and

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

DATABASE MANAGEMENT SYSTEMS LAB

(A0595104)

LAB MANUAL

RGM R-19 Regulations

Department of Computer Science and Engineering

Rajeev Gandhi Memorial College of

Engineering and Technology (Autonomous)

Nandyal, Kurnool – Dist. A.P.

RAJEEV GANDHI MEMORIAL COLLEGE OF ENGINEERING & TECHNOLOGY

(AUTONOMOUS)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VISION OF THE DEPARTMENT

To empower students with cutting edge technologies in computer science

and engineering

To train the students as entrepreneurs in computer science and

engineering to address the needs of the society

To develop smart applications to disseminate information to rural people

MISSION OF THE DEPARTMENT

To become the best computer science and engineering department in the

region offering undergraduate, post graduate and research programs in

collaboration with industry

To incubate, apply and spread innovative ideas by collaborating with

relevant industries and R & D labs through focused research groups.

To provide exposure to the students in the latest tools and technologies to

develop smart applications for the society

RGM-R-2019

R G M COLLEGE OF ENGINEERING AND TECHNOLOGY AUTONOMOUS

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

II B.Tech. II-Sem (CSE) P C

3 1.5

(A0599194) DATABASE MANAGEMENT SYSTEMS LAB

COURSE OBJECTIVES:

Student will be able to:

Create and delete database schemas and execute SQL queries

Inserting data, Altering and dropping the tables.

Various types of data conversions using the functions.

Make Use of PL/SQL variables and Language Components.

Make Use of Identifiers in PL/SQL.

Make Use of Anchored Data type.

COURSE OUTCOMES:

Upon completion of the lab, the student should be able to:

Map the model into a relational database system.

Implement the given schema on a relational DBMS.

Design, develop, and maintain Oracle Database Objects.

Use a database language for manipulating and querying data.

Develop advanced packages, stored procedures, and triggers.

Develop various functions definitions and procedures using PL/SQL.

MAPPING OF COs & POs

CO/PO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3

CO1 3 2 1

CO2 2 2 2

CO3 2 1 1 1 1

CO4 1 2 1 2

CO5 1 2 2 1

RECOMMENDED SYSTEMS/SOFTWARE REQUIREMENTS:

Intel based desktop PC

Mysql /Oracle latest version Recommended.

1) Creation, altering and dropping of tables and inserting rows into a table (use constraints while creating

tables) examples using SELECT command.

2) Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION, INTERSET,

Constraints.

Example:- Select the roll number and name of the student who secured fourth rank in the class.

3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY, HAVING

and Creation and dropping of Views.

4) Nested Queries and correlated nested queries

5) Table alterations

6) Queries using Conversion functions (to_char, to_number and to_date), string functions (Concatenation,

lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date functions (Sysdate,

next_day, add_months, last_day, months_between, least, greatest, trunc, round, to_char, to_date)

7) Creating procedures

8) Creating functions and packages

9) Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and INSTEAD

OF Triggers.

10) Introduction to ORACLE reports

REFERENCES:

1. ORACLE PL/SQL by example. Benjamin Rosenzweig, Elena Silvestrova, Pearson Education 3rd

Edition.

2. ORACLE DATA BASE LOG PL/SQL Programming SCOTT URMAN, Tata Mc-Graw Hill.

3. SQL & PL/SQL for Oracle 10g, Black Book, Dr.P.S. Deshpande.

75

Dept of CSE, RGMCET

DBMS Lab Manual Page 3

1. Creation, altering and dropping of tables and inserting rows into a table (use constraints

while creating tables) examples using SELECT command.

1. CREATE: (a)CREATE TABLE:This is used to create a new relation

Syntax: CREATE TABLE relation_name (field_1 data_type(Size),field_2 data_type(Size), .. . );

Example: SQL>CREATE TABLE Student (snoNUMBER(3)PRIMARY KEY,sname

CHAR(10),classCHAR(5));

2. ALTER: (a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing relation.

Syntax:ALTER TABLE relation_nameADD(new field_1 data_type(size), new field_2 data_type(size),..);

Example :SQL>ALTER TABLE std ADD(Address CHAR(10)); (b)ALTER TABLE...MODIFY...: This is used to change the width as well as data type of fields of existing relations.

Syntax:ALTER TABLE relation_nameMODIFY (field_1 newdata_type(Size), field_2

newdata_type(Size),....field_newdata_type(Size));

Example: SQL>ALTER TABLE student MODIFY(snameVARCHAR(10),class

VARCHAR(5));

3. DROP TABLE: This is used to delete the structure of a relation. It permanently deletes the records in the table.

Syntax: DROP TABLE relation_name;

Example: SQL>DROP TABLE std; 4. INSERT:

Syntax: INSERT INTO relation_namefield_1,field_2,.....field_n) VALUES

(&data_1,&data_2,........&data_n);

Example: SQL>INSERT INTO student(sno,sname,class,address) VALUES(&sno,’&sname’,’&class’,’&address’);

Enter value for sno: 101

Enter value for name: SIRISHA

Enter value for class: CSE

Enter value for address: Palakol

5. SELECT FROM: To display all fields for all records.

Syntax : SELECT * FROM relation_name;

Example : SQL> select * from student;

SNO SNAME CLASS ADDRESS

---- -------- ------ -------

101 SIRISHA CSE PALAKOL

102 DEVAKICSE NARSAPUR

103 KUMARCAD BHIMAVARAM

104 RAVI VLSI PALAKOL

Dept of CSE, RGMCET

DBMS Lab Manual Page 4

2. SELECT FROM: To display a set of fields for all records of relation.

Syntax: SELECT a set of fields FROM relation_name;

Example: SQL> select sno, sname from student;

SNO SNAME

---- --------

101 SIRISHA

102 DEVAKI

103 KUMAR

104 RAVI

3.SELECT - FROM -WHERE: This query is used to display a selected set of fields for a selected set of records of a relation.

Syntax: SELECT a set of fields FROMrelation_nameWHERE

condition;

Example: SQL> select * FROM student WHERE class=’CSE’; SNO SNAME CLASS ADDRESS

---- -------- ------ -------

101 SIRISHA CSE PALAKOL

102 DEVAKICSE NARSAPUR

There are 5 constraints available in ORACLE: 1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a mandatory column. It implies that a value must be entered into the column if the record is to be accepted for storage in the table.

Syntax: CREATE TABLETable_Name(column_namedata_type(size) NOT NULL, );

Example: CREATE TABLE student (snoNUMBER(3)NOT NULL, nameCHAR(10));

2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is unique i.e. a value entered in column(s) defined in the unique constraint must not be repeated across the column(s). A table may have many unique keys.

Syntax: CREATE TABLETable_Name(column_namedata_type(size) UNIQUE, ….);

Example: CREATE TABLE student (snoNUMBER(3) UNIQUE, name CHAR(10));

3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the constraint, each row in the table must make the condition either TRUE or unknown (due to a null).

Syntax: CREATE TABLETable_Name(column_namedata_type(size) CHECK(logical

expression), ….);

Example: CREATE TABLE student (snoNUMBER (3), nameCHAR(10),class

CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));

Dept of CSE, RGMCET

DBMS Lab Manual Page 5

4. PRIMARY KEY: A field which is used to identify a record uniquely. A column or combination of columns can be created as primary key, which can be used as a reference from other tables. A table contains primary key is known as Master Table.

It must uniquely identify each record in a table. It must contain unique values. It cannot be a null field. It cannot be multi port field. It should contain a minimum no. of fields necessary to be called unique.

Syntax: CREATE TABLETable_Name(column_namedata_type(size) PRIMARY KEY,

….);

Example: CREATE TABLE faculty (fcodeNUMBER(3) PRIMARY KEY,fname

CHAR(10));

5. FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To reference any primary key column from other table this constraint can be used. The table in which the foreign key is defined is called a detail table. The table that defines the primary key and is referenced by the foreign key is called the master table.

Syntax: CREATE TABLETable_Name(column_namedata_type(size) FOREIGN KEY(column_name) REFERENCEStable_name);

Example: CREATE TABLE subject (scodeNUMBER (3) PRIMARY KEY,

subname CHAR(10),fcodeNUMBER(3),

FOREIGN KEY(fcode) REFERENCE faculty );

Defining integrity constraints in the alter table command:

Syntax: ALTER TABLETable_NameADDPRIMARY KEY (column_name); Example: ALTER TABLE student ADDPRIMARY KEY (sno);

(Or)

Syntax: ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY(colname)

Example: ALTER TABLE student ADD CONSTRAINT SN PRIMARY KEY(SNO)

Dropping integrity constraints in the alter table command:

Syntax: ALTER TABLETable_NameDROPconstraint_name;

Example: ALTER TABLE student DROPPRIMARY KEY;

(or)

Syntax: ALTER TABLE student DROP CONSTRAINT constraint_name;

Example: ALTER TABLE student DROP CONSTRAINT SN;

2. Queries (along with sub Queries)

Selecting data from sailors table

Dept of CSE, RGMCET

DBMS Lab Manual Page 6

SQL> select * from sailors;

SID SNAME AGE RATING

--------- ---------- --------- ---------

22 dustin 7 45

29 brutus 1 33

31 lubber 8 55

32 andy 8 25.5

58 rusty 10 35

64 horatio 7 35

71 zorba 10 40

74 horatio 9 40

85 art 3 25.5

95 bob 3 63.5

10 rows selected.

Selecting data from reserves table 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 102 11-OCT-98

31 103 11-JUN-98

31 104 11-DEC-98

64 101 09-MAY-98

64 102 09-AUG-98

74 104 09-AUG-98

10 rows selected.

Selecting data from boat table SQL> select * from boats;

BID BNAME COLOR

--------- -------------------- ----------

101 interlake blue

102 interlake red

103 clipper green

104 marine red

Q: find the names of sailors who have reserved boat 103. SQL> select s.snamefrom sailors swhere s.sid in (select r.sid

from reserves rwhere r.bid=103);

SNAME

--------------

dustin

Dept of CSE, RGMCET

DBMS Lab Manual Page 7

lubber

2 rows selected.

Q: find the names of sailors who have reserved a red boat. SQL> select s.snamefrom sailors swhere s.sid in

(selectr.sidfrom reserves rwhere r.bid in (select b.bid

from boats bwhere b.color='red'));

SNAME

--------------------

dustin

lubber

horatio

horatio

4 rows selected.

Q: Find the name and age of the oldest sailors.

SQL> select MAX(s.age)from sailors s;

MAX(S.AGE)

----------

10

Q: Count the number of sailors. SQL> select COUNT(s.age)from sailors s

COUNT(S.AGE)

------------

10

Q: Count the number of different sailors names.

SQL> select COUNT(distinct s.sname)* from sailors s

COUNT(DISTINCTS.SNAME)

----------------------

9

Q: find the names of sailors who have not reserved a red boat. SQL> select s.sname

from sailors s

wheres.sid not in (select r.sid

from reserves r

where r.bid in (select b.bid

from boats b

where b.color='red'))

SNAME

--------

brutus

andy

rusty

zorba

Dept of CSE, RGMCET

DBMS Lab Manual Page 8

art

bob

6 rows selected.

Q: find the names of sailors who have not reserved boat 103. SQL> select s.snamefrom sailors swhere exists(select *from

reserves rwhere r.bid=103and r.sid=s.sid);

SNAME

-------

dustin

lubber

2 rows selected.

Q: find the names of sailors who have reserved at least one boat. SQL> select s.snamefrom sailors s, reserves rwhere s.sid=r.sid;

SNAME

----------

dustin

dustin

dustin

dustin

lubber

lubber

lubber

horatio

horatio

horatio

10 rows selected.

Q: Compute increments for the ratings of persons who have sailed two different boats on the

same day.

SQL> select s.sname,s.rating+1 As ratingfrom sailors s,

reserves r1, reserves r2where s.sid=r1.sid AND s.sid=r2.sid

AND r1.day=r2.day AND r1.bid<>r2.bid

SNAME RATING

-------------------- ---------

dustin 46

dustin 46

Q: Find the names of sailors who have reserved a red or a green boat. SQL> select s.snamefrom sailors s, reserves r,boats bwhere

s.sid=r.sid AND r.bid=b.bid AND (b.color='red' OR

b.color='green')

SNAME

--------------------

Dept of CSE, RGMCET

DBMS Lab Manual Page 9

dustin

dustin

dustin

lubber

lubber

lubber

horatio

horatio

8 rows selected.

Q: find the all sids of sailors who have rating 10 or have reserved boat 104.. SQL> select s.sidfrom sailors swhere s.rating=10union

selectr.sidfrom reserves rwhere r.bid=104;

SID

------

22

31

74

Q: Find the number of reservations for each red boat. SQL> select b.bid,count(*)As sailorcountfrom boats b,

reserves rwhere r.bid=b.bid AND b.color='red'group by b.bid;

BID SAILORCOUNT

--------- -----------

102 3

104 3

Q: Find the minimum age of the sailor.

SQL> select min(s.age)from sailors s;

MIN(S.AGE)

----------

1

Q: Find the sum of the rating of sailors. SQL> select sum(s.rating)from sailors s;

SUM(S.RATING)

-------------

397.5

Q: find the id and names of sailors who have reserved id=22 or age<25.

SQL> select sid,snamefrom sailors where sid=22 or age<25

SID SNAME

-- --------

22 dustin

3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP

BY, HAVING and Creation and dropping of Views.

Dept of CSE, RGMCET

DBMS Lab Manual Page 10

Aggregative operators: In addition to simply retrieving data, we often want to perform some computation or summarization. SQL allows the use of arithmetic expressions. We now consider a powerful class of constructs for computing aggregate values such as MIN and SUM. 1. Count: COUNT following by a column name returns the count of tuple in that column. If DISTINCT keyword is used then it will return only the count of unique tuple in the column. Otherwise, it will return count of all the tuples (including duplicates) count (*) indicates all the tuples of the column.

Syntax: COUNT (Column name) Example:SELECT COUNT (Sal) FROM emp;

2. SUM: SUM followed by a column name returns the sum of all the values in that column.

Syntax:SUM (Column name)

Example: SELECT SUM (Sal) From emp;

3. AVG: AVG followed by a column name returns the average value of that column values.

Syntax:AVG (n1,n2..)

Example: Select AVG(10, 15, 30) FROM DUAL;

4. MAX: MAX followed by a column name returns the maximum value of that column.

Syntax: MAX (Column name)

Example: SELECT MAX (Sal) FROM emp; SQL> select deptno,max(sal) from emp group by deptno;

DEPTNO MAX(SAL)

------ --------

10 5000

20 3000

30 2850

SQL> select deptno,max(sal) from emp group by deptno having

max(sal)<3000;

DEPTNO MAX(SAL)

----- --------

30 2850

5. MIN: MIN followed by column name returns the minimum value of that column.

Syntax: MIN (Column name) Example: SELECT MIN (Sal) FROM emp;

Dept of CSE, RGMCET

DBMS Lab Manual Page 11

SQL>select deptno,min(sal) from emp group by deptno having

min(sal)>1000;

DEPTNO MIN(SAL)

----- --------

10 1300

VIEW: In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are

fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and

present the data as if the data were coming from one single table. A view is a virtual table, which consists of a set of columns from one or more

tables. It is similar to a table but it doest not store in the database. View is a query stored as an object.

Syntax: CREATE VIEW view_name AS SELECT set of fields FROM

relation_name WHERE (Condition)

1. Example:

SQL>CREATE VIEW employee AS SELECT empno,ename,jobFROM EMP

WHERE job = ‘clerk’;

View created.

SQL> SELECT * FROM EMPLOYEE;

EMPNO ENAME JOB

---- ------ -------

7369 SMITH CLERK

7876 ADAMS CLERK

7900 JAMES CLERK

7934 MILLER CLERK

2.Example:

CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products WHERE Discontinued=No

DROP VIEW:This query is used to delete a view , which has been already created.

Syntax: DROP VIEW View_name;

Example : SQL> DROP VIEW EMPLOYEE;

View dropped

4. Queries using Conversion functions (to_char, to_number and to_date), string functions

(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr),

date functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest,

trunc, round, to_char, to_date)

1. Conversion functions:

Dept of CSE, RGMCET

DBMS Lab Manual Page 12

To_char: TO_CHAR (number) converts n to a value of VARCHAR2 data type, using the optional number format fmt. The value n can be of type NUMBER, BINARY_FLOAT, orBINARY_DOUBLE.

SQL>select to_char(65,'RN')from dual;

To_number :TO_NUMBER converts expr to a value of NUMBER datatype. SQL> Select to_number('1234.64') from Dual;

To_date: TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to a value of DATE datatype. SQL>SELECT TO_DATE('January 15, 1989, 11:00 A.M.')FROM DUAL;

2. String functions:

Concat: CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any of the datatypes SQL>SELECT CONCAT(‘ORACLE’,’CORPORATION’)FROM DUAL;

Lpad: LPAD returns expr1, left-padded to length n characters with the sequence of characters in expr2. SQL>SELECT LPAD(‘ORACLE’,15,’*’)FROM DUAL;

Rpad:RPAD returns expr1, right-padded to length n characters with expr2, replicated as many times as necessary. SQL>SELECT RPAD (‘ORACLE’,15,’*’)FROM DUAL;

Ltrim: Returns a character expression after removing leading blanks. SQL>SELECT LTRIM(‘SSMITHSS’,’S’)FROM DUAL;

Rtrim: Returns a character string after truncating all trailing blanks SQL>SELECT RTRIM(‘SSMITHSS’,’S’)FROM DUAL;

Lower: Returns a character expression after converting uppercase character data to lowercase. SQL>SELECT LOWER(‘DBMS’)FROM DUAL;

Upper: Returns a character expression with lowercase character data converted to uppercase SQL>SELECT UPPER(‘dbms’)FROM DUAL;

Length: Returns the number of characters, rather than the number of bytes, of the given string expression, excluding trailing blanks. SQL>SELECT LENGTH(‘DATABASE’)FROM DUAL;

Substr: Returns part of a character, binary, text, or image expression. SQL>SELECT SUBSTR(‘ABCDEFGHIJ’3,4)FROM DUAL;

Dept of CSE, RGMCET

DBMS Lab Manual Page 13

Instr: The INSTR functions search string for substring. The function returns an integer indicating the position of the character in string that is the first character of this occurrence. SQL>SELECT INSTR('CORPORATE FLOOR','OR',3,2)FROM DUAL;

3. Date functions:

Sysdate: SQL>SELECT SYSDATE FROM DUAL;

next_day: SQL>SELECT NEXT_DAY(SYSDATE,’WED’)FROM DUAL;

add_months: SQL>SELECT ADD_MONTHS(SYSDATE,2)FROM DUAL;

last_day: SQL>SELECT LAST_DAY(SYSDATE)FROM DUAL;

months_between: SQL>SELECT MONTHS_BETWEEN(SYSDATE,HIREDATE)FROM EMP;

Least: SQL>SELECT LEAST('10-JAN-07','12-OCT-07')FROM DUAL;

Greatest: SQL>SELECT GREATEST('10-JAN-07','12-OCT-07')FROM DUAL;

Trunc: SQL>SELECT TRUNC(SYSDATE,'DAY')FROM DUAL;

Round: SQL>SELECT ROUND(SYSDATE,'DAY')FROM DUAL;

to_char: SQL> select to_char(sysdate, "dd\mm\yy") from dual;

to_date: SQL> select to_date(sysdate, "dd\mm\yy") from dual;

Sailors(sid: integer, sname: string, rating: integer, age: real) Boats(bid: integer, bname: string, color: string) Reserves(sid: integer, bid: integer, day: date)

(Q1) Find the names of sailors who have reserved boat 103. SELECT S.snameFROM Sailors S, Reserves R WHERE S.sid = R.sidAND R.bid=103 (Q2) Find the names of sailors who have reserved a red boat. SELECT S.snameFROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sidAND R.bid = B.bidAND B.color = `red' (Q3) Find the colors of boats reserved by Lubber. SELECT B.colorFROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sidAND R.bid = B.bidAND S.sname = `Lubber' (Q4) Find the names of sailors who have reserved at least one boat. SELECT S.snameFROM Sailors S, Reserves R WHERE S.sid = R.sid (Q5) Find the names of sailors who have reserved a red or a green boat.

Dept of CSE, RGMCET

DBMS Lab Manual Page 14

SELECT S.snameFROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sidAND R.bid = B.bid AND (B.color = `red' OR B.color = `green')

(Q6) Find the names of sailors who have reserved a red and a green boat. SELECT S.snameFROM Sailors S, Reserves R1, Boats B1, Reserves R2, Boats B2 WHERE S.sid = R1.sid AND R1.bid = B1.bid AND S.sid = R2.sid AND R2.bid = B2.bid AND B1.color=`red' AND B2.color = `green' (Q7) Find the names of sailors who have reserved at least two boats.

(Q8) Find the sids of sailors with age over 20 who have not reserved a red boat.

(Q9) Find the names of sailors who have reserved all boats. SELECT S.snameFROM Sailors S WHERE NOT EXISTS (( SELECTB.bidFROM Boats B ) EXCEPT (SELECT R.bidFROM Reserves R WHERE R.sid = S.sid )) (Q10) Find the names of sailors who have reserved all boats called Interlake.

(Q11) Find all sailors with a rating above 7.

SELECT S.sid, S.sname, S.rating, S.age FROM Sailors AS S WHERE S.rating>7

(Q12) Find the names and ages of sailors with a rating above 7.

(Q13) Find the sailor name, boat id, and reservation date for each reservation.

(Q14) Find sailors who have reserved all red boats.

(Q15) Find the names and ages of all sailors. SELECT DISTINCT S.sname, S.ageFROMSailors S (Q16) Find the sids of sailors who have reserved a red boat. SELECT R.sidFROM Boats B, Reserves R WHERE B.bid = R.bidAND B.color = `red' (Q17) Compute increments for the ratings of persons who have sailed two different boats on the same day. SELECT S.sname, S.rating+1 AS rating FROM Sailors S, Reserves R1, Reserves R2 WHERE S.sid = R1.sid AND S.sid = R2.sid AND R1.day = R2.day AND R1.bid <>R2.bid (Q18) Find the ages of sailors whose name begins and ends with B and has at least three characters. SELECT S.ageFROM Sailors S WHERE S.snameLIKE `B %B'

Dept of CSE, RGMCET

DBMS Lab Manual Page 15

(Q19) Find the sids of all sailors who have reserved red boats but not green boats. SELECT S.sidFROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sidAND R.bid = B.bidAND B.color = `red' EXCEPT SELECT S2.sid FROM Sailors S2, Reserves R2, Boats B2 WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color = `green' (Q20) Find all sids of sailors who have a rating of 10 or have reserved boat 104. SELECT S.sidFROM Sailors S WHERE S.rating = 10 UNION SELECT R.sidFROM Reserves R WHERE R.bid = 104 NESTED QUERIES (Q21) Find the names of sailors who have not reserved a red boat. SELECT S.snameFROM Sailors S WHERE S.sidNOT IN ( SELECTR.sidFROM Reserves R WHERE R.bidIN ( SELECTB.bidFROM Boats B WHERE B.color = `red' ) Correlated nested queries (Q22) Find sailors whose rating is better than some sailor called Horatio. SELECT S.sidFROM Sailors S WHERE S.rating>ANY ( SELECTS2.rating FROM Sailors S2 WHERE S2.sname = `Horatio' ) (Q23) Find sailors whose rating is better than every sailor called Horatio. SELECT S.sidFROM Sailors S WHERE S.rating>ALL ( SELECTS2.rating FROM Sailors S2 WHERE S2.sname = `Horatio' ) (Q24) Find the sailors with the highest rating. SELECT S.sidFROM Sailors S WHERE S.rating>= ALL ( SELECTS2.rating FROM Sailors S2 ) (Q25) Find the average age of all sailors. SELECT AVG (S.age) FROM Sailors S (Q26) Find the average age of sailors with a rating of 10. SELECT AVG (S.age) FROM Sailors S WHERE S.rating = 10 (Q27) Find the name and age of the oldest sailor. SELECT S.sname, MAX (S.age) FROM Sailors S (Q28) Count the number of sailors. SELECT COUNT (*) FROM Sailors S (Q29) Count the number of different sailor names.

Dept of CSE, RGMCET

DBMS Lab Manual Page 16

SELECT COUNT ( DISTINCTS.sname ) FROM Sailors S (Q30) Find the names of sailors who are older than the oldest sailor with a rating of 10. SELECT S.snameFROM Sailors S WHERE S.age>( SELECT MAX ( S2.age ) FROM Sailors S2 WHERE S2.rating = 10 ) (Q31) Find the age of the youngest sailor for each rating level. SELECT S.rating, MIN (S.age) FROM Sailors S GROUP BY S.rating (Q32) Find the age of the youngest sailor who is eligible to vote (i.e., is at least 18 years old) for each rating level with at least two such sailors. SELECT S.rating, MIN (S.age) AS minageFROM Sailors S WHERE S.age>= 18 GROUP BY S.rating HAVING COUNT (*) >1 (Q33) For each red boat, find the number of reservations for this boat. SELECT B.bid, COUNT (*) AS sailorcountFROM Boats B, Reserves R WHERE R.bid = B.bid GROUP BY B.bidHAVING B.color = `red' (Q34) Find the average age of sailors for each rating level that has at least two sailors. SELECT S.rating, AVG (S.age) AS avgageFROM Sailors S GROUP BY S.ratingHAVING COUNT (*) >1 (Q35) Find the average age of sailors who are of voting age (i.e., at least 18 years old) for each rating level that has at least two sailors. SELECT S.rating, AVG ( S.age ) AS avgageFROM Sailors S WHERE S. age >= 18 GROUP BY S.rating HAVING 1 <( SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating ) (Q36) Find the average age of sailors who are of voting age (i.e., at least 18 years old) for each rating level that has at least two such sailors. SELECT S.rating, AVG ( S.age ) AS avgageFROM Sailors S WHERE S. age >18 GROUP BY S.rating HAVING 1 <( SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating AND S2.age >= 18 ) (Q37) Find those ratings for which the average age of sailors is the minimum over all ratings. SELECT S.ratingFROM Sailors S WHERE AVG (S.age) = ( SELECT MIN (AVG (S2.age)) FROM Sailors S2 GROUP BY S2.rating )

Dept of CSE, RGMCET

DBMS Lab Manual Page 17

FUNCTION

CREATING A TABLE :

SQL> create table stud(rno number(2),mark1 number(3),mark2 number(3),total

number(3),primary key(rno));

Table created.

DISPLAY TABLE STRUCTURE:

SQL> desc stud;

Name Null? Type ----------------------------------------- -------- ---------------------------- RNO NOT NULL NUMBER(2) MARK1 NUMBER(3) MARK2 NUMBER(3) TOTAL NUMBER(3)

INSERT DATA INTO THE TABLE:

SQL> insert into stud values(1,80,85,0);

1 row created.

SQL> insert into stud values(2,75,84,0);

1 row created.

SQL> insert into stud values(3,65,80,0);

1 row created.

SQL> insert into stud values(4,90,85,0);

1 row created.

SQL> select * from stud;

RNO MARK1 MARK2 TOTAL ---------- ---------- ---------- ------------------ 1 80 85 0 2 75 84 0 3 65 80 0 4 90 85 0

Dept of CSE, RGMCET

DBMS Lab Manual Page 18

CREATE FUNCTION:

SQL> create or replace function stude(rnum number) return number is

2 total number;

3 m1 number;

4 m2 number;

5 begin

6 select mark1,mark2 into m1,m2 from stud where rno=rnum;

7 total:=m1+m2;

8 return total;

9 end;

10 /

Function created.

SELECT A FUNCTION:

SQL> select stude(2) from dual;

STUDE(2)

----------

159

CREATE TABLE:

SQL> create table purchase (icode number(3),iname varchar2(13),price

number(6),quantity number(3),rate number(8),primary key(icode),unique(iname));

Table created.

Dept of CSE, RGMCET

DBMS Lab Manual Page 19

SQL> desc purchase;

Name Null? Type ----------------------------------------- -------- ---------------------------- ICODE NOT NULL NUMBER(3) INAME VARCHAR2(13) PRICE NUMBER(6) QUANTITY NUMBER(3) RATE NUMBER(8)

INSERT DATA INTO TABLE:

SQL> insert into purchase values(100,'peusat',20,10,0);

1 row created.

SQL> insert into purchase values(101,'parkerpeu',60,10,0);

1 row created.

SQL> insert into purchase values(102,'180pgnote',24,10,0);

1 row created.

SQL> insert into purchase values(103,'80pgnote',10,25,0);

1 row created.

SQL> insert into purchase values(104,'stickfile',10,20,0);

1 row created.

SQL> select * from purchase;

ICODE INAME PRICE QUANTITY RATE ---------- -------------------- ---------- ------------------- ---------- 100 PenSet 20 10 0 101 ParkerPen 60 10 0 102 180pg Note 24 10 0 103 80pg Note 10 25 0 104 StickFile 10 20 0

Dept of CSE, RGMCET

DBMS Lab Manual Page 20

CREATE FUNCTION:

SQL> create or replace function pur(itmcd number) return number is 2 qt number; 3 pr number; 4 rate number; 5 begin 6 select price,quantity into pr,qt from purchase where icode=itmcd; 7 rate:=qt*pr; 8 return rate; 9 end; 10 / Function created.

SELECT A FUNCTION:

SQL> select pur(102) from dual;

PUR(102)

-----------

240

RESULT:

Thus the PL/SQL block program using Functions is executed and verified.

Dept of CSE, RGMCET

DBMS Lab Manual Page 21

PROCEDURE

CREATING A TABLE :

SQL> create table stud(rno number(2),mark1 number(3),mark2 number(3),total

number(3),primary key(rno));

Table created.

SQL> desc stud;

Name Null? Type ---------------------------- -------- --------------------- RNO NOT NULL NUMBER(2) MARK1 NUMBER(3) MARK2 NUMBER(3) TOTAL NUMBER(3)

SQL> select * from stud;

RNO MARK1 MARK2 TOTAL ---------- ---------- ---------- ---------- 1 80 85 0 2 75 84 0 3 65 80 0 4 90 85 0

SQL> create or replace procedure studd(rnum number) is

2 m1 number;

3 m2 number;

4 total number;

5 begin

6 select mark1,mark2 into m1,m2 from stud where rno=rnum;

7 if m1<m2 then

8 update stud set total=m1+m2 where rno=rnum;

9 end if;

10 end;

11 /

Procedure created.

Dept of CSE, RGMCET

DBMS Lab Manual Page 22

SQL> exec studd(1);

PL/SQL procedure successfully completed.

SQL> select * from stud;

RNO MARK1 MARK2 TOTAL ---------- ---------- ---------- ---------- 1 80 85 165 2 75 84 0 3 65 80 0 4 90 85 0

SQL> exec studd(4);

PL/SQL procedure successfully completed.

SQL> selesct * from stud;

RNO MARK1 MARK2 TOTAL ---------- ---------- ---------- ---------- 1 80 85 165 2 75 84 0 3 65 80 0 4 90 85 0

SQL> exec studd(2);

PL/SQL procedure successfully completed.

SQL> exec studd(3);

PL/SQL procedure successfully completed.

SQL> select * from stud;

RNO MARK1 MARK2 TOTAL ---------- ---------- ---------- ---------- 1 80 85 165 2 75 84 159

Dept of CSE, RGMCET

DBMS Lab Manual Page 23

3 65 80 145 4 90 85 0 SQL> desc emp17;

Name Null? Type ----------------------- -------- -------------- ENO NOT NULL NUMBER(2) ENAME NOT NULL VARCHAR2(18) DNO NOT NULL NUMBER(3) SAL NUMBER(8) MID NUMBER(3)

SQL> select * from emp17;

ENO ENAME DNO SAL MID ------- -------------------- ---------- ---------- ---------- 1 Akshaya 102 50000 1 2 Srikantan 105 12000 1 3 Banupriya 100 32000 1 4 Chamundi 100 28000 3 5 Janani 101 24000 3 6 Subha 100 20000 4 7 Sridhar 105 35000 1 8 Shree 105 10000 2 9 Krithi 103 29000 3 9 rows selected.

SQL> create or replace procedure dnsal(enum number) is

2 s1 number;

3 sal number;

4 begin

5 select sal into s1 from emp17 where eno=enum;

6 if s1>30000 then

7 update emp17 set sal=s1+500 where eno=enum;

8 end if;

9 if s1<30000 then

10 update emp17 set sal=s1+250 where eno=enum;

11 end if;

Dept of CSE, RGMCET

DBMS Lab Manual Page 24

12 end;

13 /

Procedure created.

SQL> exec dnsal(8);

PL/SQL procedure successfully completed.

SQL> select * from emp17 where eno=8;

ENO ENAME DNO SAL MID ---------- ------------------ ---------- ---------- -------------- 8 Shree 105 10250 2

SQL> exec dnsal(1);

PL/SQL procedure successfully completed.

SQL> select * from emp17 where eno=1;

ENO ENAME DNO SAL MID ---------- ------------------ ---------- ---------- --------------- 1 Akshaya 102 50500 1

CREATING A PROCEDURE:

SQL> create or replace procedure list_emp (dept in number)

2 as

3 begin

4 for a in (select * from empl where deptno=dept)

5 loop

6 dbms_output.put_line(a.eno);

7 end loop;

8 end;

9 /

Procedure created.

Dept of CSE, RGMCET

DBMS Lab Manual Page 25

CALLING THE PROCEDURE:

SQL> execute list_emp(1001);

100

104

PL/SQL procedure successfully completed.

DROP PROCEDURE:

SQL> drop procedure list_emp;

Procedure dropped.

RESULT:

Thus the PL/SQL block program using user-defined exception handler is

executed and verified.

Dept of CSE, RGMCET

DBMS Lab Manual Page 26

PACKAGE

Creating a Package:

SQL> create or replace package emp_objects

as

cursor emp_list return employee1%rowtype;

function seniors(dept in varchar2) return varchar2;

procedure high_sal(dept in number, eno out empl.eno%type, ename out

empl.name%type);

end;

/

Package created.

Creating a Package Body

SQL> create or replace package body emp_objects as

cursor emp_list return employee1%rowtype is select * from employee1;

function seniors(dept in varchar2) return varchar2 is

cursor a is select * from employee1 where dt_join=(select min(dt_join) from

employee1 where deptid=dept);

a_var a%rowtype;

begin

open a;

fetch a into a_var;

if a%notfound then

return' No employees in the dept.';

else

return a_var.empno||','||a_var.name;

end if;

end;

procedure high_sal(dept in number, eno out empl.eno%type, ename out

empl.name%type) is

cursor a is select eno, name from empl where basic=(select max(basic) from

empl where deptno=dept);

begin

open a;

Dept of CSE, RGMCET

DBMS Lab Manual Page 27

fetch a into eno, ename;

close a;

end;

end emp_objects;

/

Package body created.

Calling the Package

declare

eno employee1.empno%type;

ename employee1.name%type;

a_var employee1%rowtype;

name varchar2(30);

begin

for c in emp_objects.emp_list

loop

emp_objects.high_sal(a_var.deptid, eno, ename);

dbms_output.put_line(a_var.deptid||' '||eno||' '||ename);

end loop;

for a1 in (select dept from departments)

loop

name:=senior(a1.dept);

dbms_output.put_line(a1.dept||' '||name);

end loop;

end;

/

SQL> @ packfunc;

d1 102,kenneth

d2 101,erich

d3 105,clive

d4 106,robin

PL/SQL procedure successfully completed.

RESULT:

Thus the PL/SQL block program using package is executed and verified.

Dept of CSE, RGMCET

DBMS Lab Manual Page 28

Trigger

TRIGGER WITH BEFORE UPDATE

Create Table

SQL> create table orders(order_id number(5),quantity number(4),cost_per_item

number(6,2),total_cost number(8,2),updated_date date,updated_by varchar2(10));

Table created.

Inserting Records

SQL> insert into orders(order_id,quantity,cost_per_item)

values(&order_id,&quantity,&cost_per_item);

Enter value for order_id: 1

Enter value for quantity: 4

Enter value for cost_per_item: 20

old 1: insert into orders(order_id,quantity,cost_per_item)

values(&order_id,&quantity,&cost_per_it

new 1: insert into orders(order_id,quantity,cost_per_item) values(1,4,20)

1 row created.

SQL> /

Enter value for order_id: 2

Enter value for quantity: 5

Enter value for cost_per_item: 30

old 1: insert into orders(order_id,quantity,cost_per_item)

values(&order_id,&quantity,&cost_per_it

new 1: insert into orders(order_id,quantity,cost_per_item) values(2,5,30)

1 row created.

SQL> /

Enter value for order_id: 3

Enter value for quantity: 6

Enter value for cost_per_item: 25

old 1: insert into orders(order_id,quantity,cost_per_item)

values(&order_id,&quantity,&cost_per_it

new 1: insert into orders(order_id,quantity,cost_per_item) values(3,6,25)

Dept of CSE, RGMCET

DBMS Lab Manual Page 29

1 row created.

SQL> select * from orders;

ORDER_ID QUANTITY COST_PER_ITEM TOTAL_COST UPDATED_D UPDATED_BY ---------- ---------- ------------- ---------- --------- -------------------------------------------------- 1 4 20 2 5 30 3 6 25

TRIGGER SCRIPT

SQL> create or replace trigger orders_before_update

2 before update

3 on orders

4 for each row

5 declare

6 v_username varchar2(10);

7 begin

8 select user into v_username from dual;

9 :new.updated_date:=sysdate;

10 :new.updated_by:=v_username;

11 end;

12 /

Trigger created.

SQL> update orders set total_cost=3000 where order_id=2;

1 row updated.

SQL> select * from orders;

ORDER_ID QUANTITY COST_PER_ITEM TOTAL_COST UPDATED_D UPDATED_BY ---------- ---------- ------------- ---------- --------- ----------------------------------------------------- 1 4 20 2 5 30 3000 19-SEP-07 CSE3101 3 6 25

Dept of CSE, RGMCET

DBMS Lab Manual Page 30

TRIGGER WITH AFTER UPDATE

Create Table

SQL> create table orders30(order_id number(5),quantity number(4),cost_per_item

number(6,2),total_cost number(8,2));

Table created.

SQL> create table orders_audit(order_id number,quantity_before

number,quantity_after number,username varchar2(20));

Table created.

Inserting Records

SQL> insert into orders30(order_id,quantity,cost_per_item)

values(&order_id,&quantity,&cost_per_item);

Enter value for order_id: 100

Enter value for quantity: 5

Enter value for cost_per_item: 10

old 1: insert into orders30(order_id,quantity,cost_per_item)

values(&order_id,&quantity,&cost_per_

new 1: insert into orders30(order_id,quantity,cost_per_item) values(100,5,10)

1 row created.

SQL> /

Enter value for order_id: 101

Enter value for quantity: 4

Enter value for cost_per_item: 20

old 1: insert into orders30(order_id,quantity,cost_per_item)

values(&order_id,&quantity,&cost_per_

new 1: insert into orders30(order_id,quantity,cost_per_item) values(101,4,20)

1 row created.

SQL> /

Enter value for order_id: 102

Enter value for quantity: 5

Enter value for cost_per_item: 30

old 1: insert into orders30(order_id,quantity,cost_per_item)

values(&order_id,&quantity,&cost_per_

Dept of CSE, RGMCET

DBMS Lab Manual Page 31

new 1: insert into orders30(order_id,quantity,cost_per_item) values(102,5,30)

1 row created.

SQL> create or replace trigger orders_after_update

AFTER UPDATE

ON orders30

for each row

declare

v_username varchar2(10);

begin

select user into v_username

from dual;

insert into orders_audit

(order_id,

quantity_before,

quantity_after,

username)

values

(:new.order_id,

:old.quantity,

:new.quantity,

v_username);

end;

/

Trigger created.

SQL> update orders30 set quantity=25 where order_id=101;

1 row updated.

SQL> select *from orders_audit;

ORDER_ID QUANTITY_BEFORE QUANTITY_AFTER USERNAME ---------- --------------- -------------- --------------------------------------------------------- 101 4 25 CSE3090

Dept of CSE, RGMCET

DBMS Lab Manual Page 32

AIM:

To write a PL/SQL program to display the old and new values of a record

after updating using triggers.

PROGRAM:

create or replace trigger xxx after update on siva

for each row

begin

dbms_output.put_line('mark1 old value:'||:old.mark1);

dbms_output.put_line('mark2 new value:'||:new.mark1);

dbms_output.put_line('mark2 old value:'||:old.mark2);

dbms_output.put_line('mark2 new value:'||:new.mark2);

dbms_output.put_line('mark3 old value:'||:old.mark3);

dbms_output.put_line('mark3 new value:'||:new.mark3);

end;

SAMPLE INPUT OUTPUT:

SQL>/

Trigger created.

SQL> update siva set mark1=90,mark2=89,mark3=99 where rlno=2;

mark1 old value:99

mark2 new value:90

mark2 old value:78

mark2 new value:89

mark3 old value:67

mark3 new value:99

Dept of CSE, RGMCET

DBMS Lab Manual Page 33

1 row updated.

SQL> select * from siva;

RLNO NAME MARK1 MARK2 MARK3 -------------------------- ----- ---------- ---------- ------------------ 1 ramya 100 98 87 2 siva 99 78 67 3 sang 75 87 65

SQL> select * from siva;

RLNO NAME MARK1 MARK2 MARK3 ---------- --------------------- ---------- ---------- ---------- 1 ramya 100 98 87 2 siva 90 89 99 3 sang 75 87 65

RESULT:

Thus the PL/SQL block program using triggers is executed and verified.

RAJEEV GANDHI MEMORIAL COLLEGE OF ENGINEERING & TECHNOLOGY

(AUTONOMOUS)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Evaluation Procedure for Internal Laboratory Examinations:

1. Of the 25 marks for internal, 10 marks will be awarded for day-to-day work and 10 marks

to be awarded for the Record work and 5 marks to be awarded by conducting an internal

laboratory test.

2. Concerned Teachers have to do necessary corrections with explanations.

3. Concerned Lab teachers should enter marks in index page.

4. Internal exam will be conducted by two Staff members.

Dr.K. Subba Reddy

Professor & Head Dept. of CSE.

RAJEEV GANDHI MEMORIAL COLLEGE OF ENGINEERING & TECHNOLOGY

(AUTONOMOUS)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Evaluation Procedure for External Laboratory Examinations:

1. For Practical subjects there is a continuous evaluation during the semester for 25 Sessional

marks and 50 end examination marks.

2. The end examination shall be conducted by the teacher concerned (Internal Examiner) and

another External Examiner, recommended by Head of the Department with the approval of

principal.

Evaluation procedure for external lab examination:

1. Procedure for the program ---------- 20M

2. Execution of the program ---------- 15M

3. Viva voce ---------- 15M

----------------------------

Total 50M

-----------------------------

Dr.K. Subba Reddy

Professor & Head Dept. of CSE.