100% found this document useful (1 vote)
172 views

DBMS Lab programs 4th sem

Uploaded by

Satyam Amrutkar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
172 views

DBMS Lab programs 4th sem

Uploaded by

Satyam Amrutkar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

CMR College Of Engineering & Technology

Dept Of CSE

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

DATABASE MANAGEMENT SYSTEM LAB MANUAL


Subject Code : A405508
Regulation : R-22

Academic Year : 2023-2024

II B. TECH IV SEMESTER

COMPUTER SCIENCE AND ENGINEERING


DEPT OF CSE

CSE
CMR College Of Engineering & Technology
Dept Of CSE

CO-REQUISITES:
“Database Management System”

COURSE OBJECTIVES:

1. Introduce ER data model, database design and normalization


2. Learn SQL basics for data definition and data manipulation

Course Outcomes:
 Design database schema for a given application and apply normalization
 Acquire skills in using SQL commands for data definition and data manipulation.
 Develop solutions for database applications using procedures, cursors and trig

CSE
CMR College Of Engineering & Technology
Dept Of CSE

Course Name: DBMS LAB Course Code: A405508


Year/Semester:2nd year/ IV SEM Regulation: R-22

List of Experiments:
1. Concept design with E-R Model
Draw an ER diagram for the following

a. There are two entity sets Employee and Department. These entity sets are
participating in a relationship works in. The relationship set is converted into
relation with attributes EmpNo from Employee relation, D_id from Department
relation and Since, the attribute of the relationship set itself.

2. Relational Model
a. Convert the above ER diagram into Relational Model

3. Normalization

Eid E.Nam Ph.no ProjI ProjNam ProjLeade EmpCity City


e d e r Zip
101 John 98765623,9982341 P03 Project1 Grey ModelTow 110033
23 03 n
102 John 89023467 P01 Project1 Christian Badarpur 110044
01
103 Ryan 76213908 P04 Project1 Hudson Naraina 110028
04
104 stephin 98132452 P02 Project1 Petro HariNagar 110064
e 02
Consider the following table.

a) Normalize the given Relation. Consider the given schema is in first


normal form and Schema(Student id ,Student name, Project Id, Project
name, City, country, ZIP) Primarykey(Student id,Project id)
Fd’s: Project Id- Project
CSE
CMR College Of Engineering & Technology
Dept Of CSE
name country-ZIP,ZIP

b)Normalize the given Table to the


BCNF Consider the set of
Functional Dependencies..

Eid EName, Ph.no, Empcity, CityZipPrimaryKey = (EmpId,


ProjId) ProjIdProjName, ProjLeader
EmpId,ProjIdProjLea
der EmpCityCityZip
ProjIdProjLeader
4. Practicing

DDLcommands
5.Practicing
DMLcommands
1.a. Create a user and grant all permissions to the user.
b. Insert the any three records in the employee table and use rollback. Check the result.
c. Add primary key constraint and not null constraint to the employee table.
d. d.Insert null values to the employee table and verify the result.
2.a. Create a user and grant all permissions to the user.
b. Insert values in the department table and use commit.
c. Add constraints like unique and not null to the department table.
d. Insert repeated values and null values into the table.
3.a. Create a user and grant all permissions to the user.
b. Insert values into the table and use commit.
c. Delete any three records in the department table and use rollback.
d. Add constraint primary key and foreign key to the table
4.a. Create a user and grant all permissions to the user.
b. Insert records in the sailor table and use commit.
c. Add save point after insertion of records and verify save point.
d. Add constraints not null and primary key to the sailor table.
5.a. Create a user and grant all permissions to
the user.
b. Use revoke command to remove user
permissions.
c. Change password of the user created.
d. Add constraint foreign key and not null.

6.a. Create a user and grant all permissions to the user.


b. Update the table reserves and use savepoint and rollback.

CSE
CMR College Of Engineering & Technology
Dept Of CSE
c. Add constraint primary key , foreign key and not null to the reserves table
d. Delete constraint not null to the table column

6.A. Querying (using ANY, ALL, UNION, INTERSECT, JOIN, Constraints etc.)
6.B. Nested, Correlated subqueries

A. Find the Sid’s of sailors who have reserved a red or a green boat.
B. Find the names of sailors who have reserved a red and a green boat.
C. Find the names of sailors who have reserved a red but not green boats.
D. Find all sids of sailors who have a rating of 10 or reserved boat 104.
E. Find the names of sailors who have reserved boat 103 using independent nested
query.
F. Find the names of sailors who have reserved a red boat.
G. Find the names of sailors who have not reserved a red boat.
1. Find the names of sailors who have reserved boat number 103 using correlated
nestedquery.

H. Find sailors whose rating is better than some sailor called ‘Horatio’.
I. Find the sailors with the highest rating.
1. Find the names of sailors who have reserved both a red and a green boat using
nestedqueries.
J. Find the names of sailors who have reserved all boats.

7. Queries using Aggregate functions, GROUP BY, HAVING and Creation and
dropping of Views.
a. who is the youngest sailor
b. Find the name of the sailor who have maximum rating
c. What is the average rating of all Sailors
d. how many sailors are there with the rating above 7
e. The following SQL lists the number of customers in each country, sorted high to low
f. The following SQL lists the number of customers in each country, sorted high to low
(Only include countries with more than 5 customers):

8.Triggers (Creation of insert trigger, delete trigger, update trigger)


1.
a. Create a pl/sql trigger which will calculate the total marks and percentage of students
after insert/update the details of a student in database.
b. Write a trigger that keeps backup of deleted records of emp_trig table.
Deleted records of emp_trigger inserted in emp_backup table.

2. Creation of insert trigger, delete trigger, update trigger practice triggers using the
passenger database. Passenger (Passport_ id INTEGER PRIMARY KEY, Name
CSE
CMR College Of Engineering & Technology
Dept Of CSE
VARCHAR (50) Not NULL, Age Integer Not NULL, Sex Char, Address
VARCHAR (50) Not NULL);
a. Write a Insert Trigger to check the Passport_id is exactly six digits or not.
b. Write a trigger on passenger to display messages ‘1 Record is inserted’, ‘1 record
is deleted’, ‘1 record is updated’ when insertion, deletion and updation are done on
passenger respectively.

9. Procedures and functions


a. Create a procedure which displays employee salary for given employee number using
out variable
b. Write a pl/sql block which displays the department name for department 40.
c. Create a procedure to check whether the given number is prime or not
d. Create a function which returns week day of a given date
e. Create a function which returns number of sailors for a given rating level.
f. Create a procedure to find the lucky number of a given birth date
g. Create a function which returns average age of sailors for a given rating level.

10.Usage of Cursors
a. Display the employee names and their salary for the accepted department number.
b. Display the top N earners for an accepted department number.
c. To write a Cursor to display the list of employees who are working as a Managers or
Analyst.
d. write a Cursor to find employee with given job and deptno.
e. Write a PL/SQL block using implicit cursor that will display message, the salaries
of all the employees in the ‘employee’ table are updated. If none of the employee’s
salary are updated we get a message 'None of the salaries were updated'. Else we
get a message like for example, 'Salaries for 1000 employees are updated' if there
are 1000 rows in ‘employee’table.
11.Packages
a. creates HR package which contains Hire and Fire functions.
Hire function adds the details of employee and Fire function deletes the details of Employee.

FACULTY HOD CSE

CSE
CMR College Of Engineering & Technology
Dept Of CSE

1.Concept design with E-R Model


Draw an ER diagram for the following

a. There are two entity sets Employee and Department. These entity sets are participating in a
relationship works in. The relationship set is converted into relation with attributes
EmpNo from Employee relation, D_id from Department relation and Since, the attribute of the
relationship set itself.

2.Relational Model
a. Convert the above ER diagram into Relational Model.

ER Diagram for Employee and Department


CMR College Of Engineering & Technology
Dept Of CSE

2.Relational Model

+------------+ +--------------+
| Employee | | Department |
+------------+ +--------------+
| EmpNo | | D_id |
| Name | | Name |
| ... | | ... |
+------------+ +--------------+
| |
| works in |
|---------------------|
| Since |
|---------------------|
|
+------------+
| Works_in |
+------------+
| EmpNo (FK) |
| D_id (FK) |
| Since |
CMR College Of Engineering & Technology
Dept Of CSE
To convert the Entity-Relationship (ER) diagram into a relational model, we need to
translate each entity set and relationship set into a table, considering the attributes and
relationships involved. Here's how we can do it:

Employee Table:
 Attributes: EmpNo (Primary Key), Name, and any other relevant attributes.

 Employee(EmpNo PRIMARY KEY, Name, ...)

Department Table:
 Attributes: D_id (Primary Key), Name, and any other relevant attributes.
Department(D_id PRIMARY KEY, Name, ...)

Works_in Table: Attributes: EmpNo (Foreign Key referencing Employee), D_id (Foreign
Key referencing Department), Since

3. Normalization

Eid E.Name Ph.no ProjId ProjName ProjLeader EmpCity City


Zip
1 John 98765623,998234123 P03 Project103 Grey ModelTown 11
0 00
1 33
1 John 89023467 P01 Project101 Christian Badarpur 11
0 00
2 44
1 Ryan 76213908 P04 Project104 Hudson Naraina 11
0 00
3 28
1 stephine 98132452 P02 Project102 Petro HariNagar 11
0 00
4 64
Consider the following table.

c) Normalize the given Relation. Consider the given schema is in first normal form and
Schema(Student id ,Student name, Project Id, Project name, City, country, ZIP)
Primarykey(Student id,Project id)
Fd’s: Project Id- Project
name country-ZIP,ZIP

d) Normalize the given Table to the BCNF


Consider the set of Functional Dependencies..
CMR College Of Engineering & Technology
Dept Of CSE
Eid EName, Ph.no, Empcity, CityZipPrimaryKey = (EmpId, ProjId)
ProjIdProjName, ProjLeader
EmpId,ProjIdProjLeader
EmpCityCityZip
ProjIdProjLeader

From this table, we can identify the following FDs:

1. Eid -> E.Name, Ph.no, EmpCity, City Zip


2. ProjId -> ProjName, ProjLeader

To normalize the given relation, we'll follow the normalization steps:

1. First Normal Form (1NF): Ensure that each attribute contains atomic values, meaning no
multi-valued attributes or repeating groups. The given table seems to be in 1NF already, as
there are no multi-valued attributes.
2. Second Normal Form (2NF): Make sure that every non-prime attribute is fully functionally
dependent on the primary key.

The primary key seems to be (Eid, ProjId). Let's create two relations:

Relation 1: (Eid, E.Name, Ph.no, EmpCity, City Zip) Relation 2: (ProjId, ProjName, ProjLeader)

3. Third Normal Form (3NF): Ensure that there are no transitive dependencies.

Both relations seem to be in 3NF already, as there are no transitive dependencies.

So, the normalized relations would be:

Relation 1: (Eid, E.Name, Ph.no, EmpCity, City Zip) Relation 2: (ProjId, ProjName, ProjLeader)

These relations are now in 2NF and 3NF, respectively, and they are normalized.

b. To normalize the given table to Boyce-Codd Normal Form (BCNF), we need to start by identifying
the candidate keys and then decompose the relation to eliminate any dependencies that violate BCNF.

Given the functional dependencies:

 Eid -> EName, Ph.no, EmpCity, CityZip


 ProjId -> ProjName, ProjLeader
 EmpId, ProjId -> ProjLeader
CMR College Of Engineering & Technology
Dept Of CSE
 EmpCity -> CityZip
 ProjId -> ProjLeader

Let's proceed with normalization:

1. Identify Candidate Keys: We have the following candidate keys based on the given
functional dependencies:
 {Eid, ProjId}
 {EmpCity}
2. Decompose into BCNF: We need to check if there are any dependencies where the
determinant is not a superkey.
a. Eid -> EName, Ph.no, EmpCity, CityZip
 This dependency is fine as Eid is a part of the candidate key.
b. ProjId -> ProjName, ProjLeader
 This dependency is also fine as ProjId is a part of the candidate key.
c. EmpId, ProjId -> ProjLeader
 Since {EmpId, ProjId} is a candidate key, this dependency is also fine.
d. EmpCity -> CityZip
 This dependency is problematic. EmpCity is not a superkey, and CityZip is not a subset
of any candidate key. So, we need to decompose this dependency.
e. ProjId -> ProjLeader
 This dependency is already fine.
3. Decompose Dependency (d): We decompose the relation using the problematic dependency
EmpCity -> CityZip.
New Relation 1: (EmpCity, CityZip)
Original Relation: (Eid, EName, Ph.no, EmpCity, CityZip, ProjId, ProjName, ProjLeader, EmpId)
4. Final Relations: We have two relations now:
 Relation 1: (EmpCity, CityZip)
 Relation 2: (Eid, EName, Ph.no, EmpCity, ProjId, ProjName, ProjLeader, EmpId)
Both relations are in BCNF, as each determinant is a superkey.

So, after normalization, we have decomposed the original relation into two relations, ensuring that
each relation satisfies BCNF.
4.Practicing DDL commands
a.Create a table called Employee with the following structure.

Name Type
Empno int
Ename Varchar2(10)
Job Varchar2(10)
Mgr int
Sal int

b.Add a column commission with domain to the Employee table with Alter command.
c. Truncate the rows from Employee table
CMR College Of Engineering & Technology
Dept Of CSE
d. Drop table;.

SOLUTION:
SQL> create table employee(empno int,ename varchar2(10),job
varchar2(10),mgr int,sal int);
Table created.
SQL> desc employee;
Name Null? Type

EMPNO

Integer
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR Integer
SAL Integer

b.Add a column commission with domain to the Employee table.

SQL> alter table employee add(commission


number);
Table altered.

SQL> desc employee;

Name Type
EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR NUMBER
SAL NUMBER
CMR College Of Engineering & Technology
Dept Of CSE

COMMISSION NUMBER

DROP: Drop command used to drop table from database

Syntax:
DROP TABLE table_name;

TRUNCATE:
Syntax: TRUNCATE TABLE table_name;
CMR College Of Engineering & Technology
Dept Of CSE

5.Practicing DML commands

1. a. Create a user and grant all permissions to the user.

CREATE USER 'Administrator'@'localhost' IDENTIFIED BY 'abc@123';


GRANT ALL PRIVILEGES ON *. * TO 'Administrator'@'localhost';
FLUSH PRIVILEGES;

b. Insert the any three records in the employee table and use rollback. Check the
result.

1. A table named employee with appropriate columns (e.g., id, name, department, etc.) is created by using
following syntax

CREATE TABLE employee (


id INT
name VARCHAR(255)
department VARCHAR(50)
);

2. Insert three records:

START TRANSACTION;

INSERT INTO employee (id,name, department) VALUES (1,'John Doe', 'Marketing');

INSERT INTO employee (id,name, department) VALUES (2,'Jane Smith', 'Sales');


INSERT INTO employee (id,name, department) VALUES (3,'Peter Brown', 'Engineering');

3. Verify the inserted records:

SELECT * FROM employee;

This query should display the three inserted records.


CMR College Of Engineering & Technology
Dept Of CSE

4. Rollback the changes:

ROLLBACK;

5. Verify the table again:

SQL
SELECT * FROM employee;

This query should now show an empty table, as the rollback has undone the previous inserts.

c. Add primary key constraint and not null constraint to the employee table.

-- Add primary key constraint to the 'id' column


ALTER TABLE employee
ADD PRIMARY KEY (id);

-- Add not null constraint to the 'name' column


ALTER TABLE employee
MODIFY COLUMN name VARCHAR(100) NOT NULL;

-- Add not null constraint to the 'department' column


ALTER TABLE employee
MODIFY COLUMN department VARCHAR(100) NOT NULL;

d. Insert null values to the employee table and verify the result.

INSERT INTO employee (id,name, department) VALUES


(NULL,’Rose Tisan’,'Engineering’),
(2,'John Doe',NULL),
(3,NULL,'HR’);
CMR College Of Engineering & Technology
Dept Of CSE
-- Verify the result
SELECT * FROM employee;

2. a. Create a department table.


CREATE TABLE department (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);

b. Insert values in the department table and use commit.


START TRANSACTION;

-- Insert values into the department table


INSERT INTO department (name) VALUES
('Engineering'),
('HR'),
('Marketing');

-- Commit the transaction


COMMIT;

c. Add constraints like unique and not null to the department table.
-- Add unique constraint to the 'name' column
ALTER TABLE department
ADD CONSTRAINT unique_department_name UNIQUE (name);

-- Add not null constraint to the 'name' column


ALTER TABLE department
MODIFY COLUMN name VARCHAR(100) NOT NULL;

d. Insert repeated values and null values into the table.


INSERT INTO department (name) VALUES
CMR College Of Engineering & Technology
Dept Of CSE
('Engineering'),
('HR'),
('Engineering'); -- Attempting to insert a repeated value

-- Attempt to insert null values into the department table


INSERT INTO department (name) VALUES
('Marketing'),
(NULL); -- Attempting to insert a null value

c. Delete any three records in the department table and use rollback.
-- Begin transaction
START TRANSACTION;

-- Delete three records from the department table


DELETE FROM department WHERE id IN (SELECT id FROM department LIMIT 3);

-- View the current state of the department table


SELECT * FROM department;

-- Rollback the transaction to restore the deleted records


ROLLBACK;

d. Add constraint primary key and foreign key to the table


-- Add primary key constraint to the 'id' column
ALTER TABLE department
ADD CONSTRAINT pk_department_id PRIMARY KEY (id);

-- Add foreign key constraint to the 'department_id' column in another table


(assuming another table named 'employee')
ALTER TABLE employee
ADD CONSTRAINT fk_employee_department_id
FOREIGN KEY (department_id) REFERENCES department(id);

4. a. Create a table sailor.


CREATE TABLE SAILORS (
CMR College Of Engineering & Technology
Dept Of CSE
SID INT PRIMARY KEY,
SNAME VARCHAR(20),
AGE INT,
RATING INT
);
b. Insert records in the sailor table and use commit.
-- Begin transaction
START TRANSACTION;

-- Insert records into the SAILORS table


INSERT INTO SAILORS (SID, SNAME, AGE, RATING) VALUES
(101, 'John', 25, 8),
(102, 'Alice', 22, 7),
(103, 'Bob', 28, 6);

-- Commit the transaction


COMMIT;

c. Add save point after insertion of records and verify save point.
-- Begin transaction
START TRANSACTION;

-- Insert records into the SAILORS table


INSERT INTO SAILORS (SID, SNAME, AGE, RATING) VALUES
(101, 'John', 25, 8),
(102, 'Alice', 22, 7),
(103, 'Bob', 28, 6);

-- Add a savepoint
SAVEPOINT after_insertion;

-- Verify the existence of the savepoint


SHOW VARIABLES LIKE 'innodb_version';

d. Add constraints not null and primary key to the sailor table.
CMR College Of Engineering & Technology
Dept Of CSE
ALTER TABLE SAILORS
MODIFY SID INT PRIMARY KEY,
MODIFY SNAME VARCHAR(20) NOT NULL,
MODIFY AGE INT NOT NULL,
MODIFY RATING INT NOT NULL;

5. a. Create a user and grant all permissions to the user.


-- Step 1: Create the user
CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'password';

-- Step 2: Grant all privileges to the user


GRANT ALL PRIVILEGES ON *.* TO 'new_user'@'localhost';

-- Step 3: Flush privileges to apply changes


FLUSH PRIVILEGES;

b. Use revoke command to remove user permissions.


-- Revoke all privileges from the user
REVOKE ALL PRIVILEGES ON *.* FROM 'new_user'@'localhost';

-- Remove the user


DROP USER 'new_user'@'localhost';

c. Change password of the user created.


SET PASSWORD FOR 'new_user'@'localhost' = PASSWORD('new_password');

6. a. Create a table reserves.


CREATE TABLE RESERVES(SID INT,BID INT,DAY DATE,FOREIGN KEY SID REFERENCES
SAILORS(SID),FOREIGN KEY BID REFERENCES BOATS(BID));
b. Update the table reserves and use savepoint and rollback.
-- Begin transaction
START TRANSACTION;

-- Update the RESERVES table


UPDATE RESERVES SET DAY = '2024-02-28' WHERE SID = 101;

-- Add a savepoint
SAVEPOINT update_savepoint;

-- Rollback to the savepoint


ROLLBACK TO SAVEPOINT update_savepoint;
CMR College Of Engineering & Technology
Dept Of CSE

c. Add constraint primary key , foreign key and not null to the reserves table
-- Add primary key constraint to the (SID, BID) combination
ALTER TABLE RESERVES
ADD CONSTRAINT pk_reserves PRIMARY KEY (SID, BID);

-- Add foreign key constraint to the 'SID' column referencing the 'SID' column in
the 'SAILORS' table
ALTER TABLE RESERVES
ADD CONSTRAINT fk_reserves_sid FOREIGN KEY (SID) REFERENCES SAILORS(SID);

-- Add foreign key constraint to the 'BID' column referencing the 'BID' column in
the 'BOATS' table
ALTER TABLE RESERVES
ADD CONSTRAINT fk_reserves_bid FOREIGN KEY (BID) REFERENCES BOATS(BID);

-- Add not null constraint to the 'DAY' column


ALTER TABLE RESERVES
MODIFY COLUMN DAY DATE NOT NULL;

d. Delete constraint not null to the table column


-- Remove the NOT NULL constraint from the 'DAY' column
ALTER TABLE RESERVES
MODIFY COLUMN DAY DATE NULL;
CMR College Of Engineering & Technology
Dept Of CSE

6.A. Querying (using ANY, ALL, UNION, INTERSECT, JOIN,


Constraints etc.)
6.B. Nested, Correlated subqueries
CREATE TABLE SAILORS (SID NUMBER(3) PRIMARY KEY, SNAME VARCHAR2(20),AGE NUMBER(3), RATING NUMBER(2));
CREATE TABLE BOATS (BID NUMBER(3) PRIMARY KEY, BNAME VARCHAR2(20),BCOLOR VARCHAR(10));
CREATE TABLE RESERVES(SID NUMBER(3),BID NUMBER(3),DAY DATE,FOREIGN KEY (SID) REFERENCES
SAILORS(SID),FOREIGN KEY (BID) REFERENCES BOATS(BID));
Output:
Table created.
Table created.
Table created.
Insert the following data into above created tables.

Sailors Data:
INSERT INTO SAILORS VALUES (22,'Dustin',7,45);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (29,'Brutus',1,33);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (31,'Lubber',8,55.5);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (32,'Andy',8,25.5);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (58,'Rusty',10,35);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (64,'Horatio',7,35);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (71,'Zorba',10,16);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (74,'Horatio',9,35);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (85,'Art',3,25.5);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (95,'Bob',3,63.5);
1 row(s) inserted.
Boats Data:
CMR College Of Engineering & Technology
Dept Of CSE
Insert into Boats values (101,'Interlake','blue');
1 row(s) inserted.
Insert into Boats values (102,'Interlake','red');
1 row(s) inserted.
Insert into Boats values (103,'Clipper','green');
1 row(s) inserted.
Insert into Boats values (104,'Marine','red');
1 row(s) inserted.
Reserves Data:
insert into Reserves values(22,101,'1998-10-10');
1 row(s) inserted.
insert into Reserves values(22,102,'1998-10-10');
1 row(s) inserted.
insert into Reserves values(22,103,'1998-08-10');
1 row(s) inserted.
insert into Reserves values(22,104,'1998-07-10');
1 row(s) inserted.
insert into Reserves values(31,102,'1998-11-10');
1 row(s) inserted.
insert into Reserves values(31,103,'1998-11-10');
1 row(s) inserted.
insert into Reserves values(31,104,'1998-12-11');
1 row(s) inserted.
insert into Reserves values(64,101,'1998-05-09');
1 row(s) inserted.
insert into Reserves values(64,102,'1998-08-09');
1 row(s) inserted.
SELECT * FROM SAILORS;
SELECT * FROM BOATS;
SELECT * FROM RESERVES;
Output:

A. Find the Sid’s of sailors who have reserved a red or a green boat.
SELECT DISTINCT s.SID
FROM Sailors s
JOIN Reserves r ON s.SID = r.SID
JOIN Boats b ON r.BID = b.BID
WHERE b.Color = 'red' OR b.Color = 'green';
CMR College Of Engineering & Technology
Dept Of CSE

B. Find the names of sailors who have reserved a red and a green boat.
SELECT s.SNAME
FROM SAILORS s,reserves r,boats b where s.sid=r.sid and r.bid=b.bid and
b.bcolor=’red’INTERSECT select s1.sname from sailors s1,reserves r1,boats b1 where
s1.sid=r1.sid and r1.bid=b1.bid and b1.bcolor=’green’);

C. Find the names of sailors who have reserved a red but not green boats.
SELECT s.SNAME
FROM sailor s reserves r,boats b where s.sid=r.sid and r.bid=b.bid and
b.bcolor=’red’
EXCEPT
select s1.sname from sailor s1,reserves r1,boats b1 where s1.sid=r1.sid and
r1.bid=b1.bid and b1.bcolor=’green’);

D. Find all sids of sailors who have a rating of 10 or reserved boat 104.
-- Find sailors with rating 10
SELECT SID
FROM SAILORS
WHERE RATING = 10

UNION

-- Find sailors who reserved boat 104


SELECT SID
FROM RESERVES
WHERE BID = 104;
CMR College Of Engineering & Technology
Dept Of CSE

E. Find the names of sailors who have reserved boat 103 using independent nested
query.
SELECT SNAME
FROM SAILORS
WHERE SID IN (
SELECT SID
FROM RESERVES
WHERE BID = 103
);

F. Find the names of sailors who have reserved a red boat.


SELECT s.sname from sailors s where s.sid IN(select r.sid from reserves r where
r.bid IN(select b.bid from boats b where b.bcolor=’red’));

G. Find the names of sailors who have not reserved a red boat.
Select s.sname from sailors s where s.sid NOT IN(select r.sid from reserves r
where r.bid NOT IN(select b.bid from boats b where b.bcolor=’red’));

H. Find the names of sailors who have reserved boat number 103 using
correlat2 ed nested query.
SELECT SNAME
FROM SAILORS s
WHERE EXISTS (
SELECT *
FROM RESERVES r
WHERE r.bid=103 and r.sid=s.sid);
CMR College Of Engineering & Technology
Dept Of CSE

I. Find sailors whose rating is better than some sailor called ‘Horatio’.
Select * from sailors s where s.rating > any(select s1.rating from sailor s1 where
s1.name=’Horatio’);

J. Find the sailors with the highest rating.


SELECT SNAME
FROM SAILORS
WHERE RATING = (
SELECT MAX(RATING)
FROM SAILORS
);

j. Find the names of sailors who have reserved both a red and a green boat
using nested queries.
SELECT SNAME
FROM SAILORS
WHERE SID IN (
SELECT R1.SID
FROM RESERVES R1
INNER JOIN BOATS B1 ON R1.BID = B1.BID
WHERE B1.BCOLOR = 'red'
) AND SID IN (
SELECT R2.SID
FROM RESERVES R2
INNER JOIN BOATS B2 ON R2.BID = B2.BID
WHERE B2.BCOLOR = 'green'
);
CMR College Of Engineering & Technology
Dept Of CSE

J. Find the names of sailors who have reserved all boats.


SELECT SNAME
FROM SAILORS
WHERE SID IN (
SELECT SID
FROM RESERVES
GROUP BY SID
HAVING COUNT(DISTINCT BID) = (SELECT COUNT(*) FROM BOATS)
);
CMR College Of Engineering & Technology
Dept Of CSE

7.Queries using Aggregate functions, GROUP BY, HAVING and


Creation and dropping of Views.

a. who is the youngest sailor


SELECT SNAME
FROM SAILORS
WHERE AGE = (SELECT MIN(AGE) FROM SAILORS);

b.Find the name of the sailor who have maximum rating


SELECT SNAME
FROM SAILORS
WHERE RATING = (SELECT MAX(RATING) FROM SAILORS);

c.What is the average rating of all Sailors


SELECT AVG(RATING) AS average_rating
FROM SAILORS;

d. how many sailors are there with the rating above 7


SELECT COUNT(*) AS sailors_above_7
FROM SAILORS
WHERE RATING > 7;
CMR College Of Engineering & Technology
Dept Of CSE

e. The following SQL lists the number of customers in each country, sorted
high to low
mysql> create table customer1(customer_id int,customer_name
varchar(10),contact int,age int,city varchar(10),country varchar(10));
Query OK, 0 rows affected (0.03 sec)

mysql> insert into customer1 values(5,'john',123,32,'bdr','IND');


Query OK, 1 row affected (0.04 sec)

mysql> insert into customer1 values(6,'smith',345,33,'bihar','PAK');


Query OK, 1 row affected (0.01 sec)

mysql> insert into customer1 values(7,'kevin',678,34,'UP','LONDON');


Query OK, 1 row affected (0.00 sec)

mysql> create or replace view country_view AS select country,count(*) as


number_of_customers from customer1 group by country order by
number_of_customers DESC;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from country_view;


+---------+---------------------+
| country | number_of_customers |
+---------+---------------------+
| IND | 1|
| PAK | 1|
| LONDON | 1|
+---------+---------------------+
3 rows in set (0.01 sec)
CMR College Of Engineering & Technology
Dept Of CSE

f. The following SQL lists the number of customers in each country, sorted
high to low (Only include countries with more than 5 customers):
create or replace view country_view AS select country,count(*) as
number_of_customers from customer1 group by country having count(*)>5 order by
number_of_customers DESC;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from country_view;

9. Procedures and functions

//emp procedure
CREATE TABLE emp (Eid INT PRIMARY KEY, Sal INT);
DROP TABLE emp;

INSERT INTO emp VALUES(101, 10000);


INSERT INTO emp VALUES(102, 20000);
INSERT INTO emp VALUES(103, 30000);

CREATE OR REPLACE PROCEDURE esal


(id IN emp.Eid%TYPE, sl OUT emp.Eid%TYPE) IS
BEGIN
SELECT Sal INTO sl FROM emp WHERE Eid=id;
dbms_output.put_line('Salary'||sl);
END esal;

DECLARE
sl INT;
id INT;
BEGIN
id := :id;
esal(id, sl);
END
CMR College Of Engineering & Technology
Dept Of CSE

//greeting procedure
CREATE OR REPLACE PROCEDURE greeting AS
BEGIN
dbms_output.put_line('hello');
END

BEGIN
greeting;
END

//department procedure
CREATE TABLE dept (Did INT PRIMARY KEY, Dname VARCHAR(10));
DROP TABLE dept;
INSERT INTO dept VALUES(101, 'IT');
INSERT INTO dept VALUES(102, 'HR');
INSERT INTO dept VALUES(103, 'Finance');

CREATE OR REPLACE PROCEDURE depname


(id IN dept.Did%TYPE, name OUT dept.Dname%TYPE) IS
BEGIN
SELECT Dname INTO name FROM dept WHERE Did=id;
dbms_output.put_line('Dept Name: '||name);
END depname;

DECLARE
id INT;
name VARCHAR(10);
BEGIN
id := :id;
depname(id, name);
END;

//isPrimeNumber Procedure
CREATE OR REPLACE PROCEDURE isprime
(A IN INT) IS
FLAG INT := 0;
BEGIN
FOR COUNTER IN 2..A-1 LOOP
IF A MOD COUNTER = 0 THEN dbms_output.put_line('Not Prime'); FLAG:=1; EXIT;
END IF;
END LOOP;
IF FLAG = 0 THEN
dbms_output.put_line('Prime');
END IF;
END isprime;
CMR College Of Engineering & Technology
Dept Of CSE

DECLARE
A INT;
BEGIN
A:= :A;
isprime(A);
END;

//weekday function (IMP!! == format for passing date is MM-DD-YYYY)


CREATE OR REPLACE FUNCTION weekday
(date IN DATE) RETURN VARCHAR IS
day VARCHAR(10);
BEGIN
day := TO_CHAR(date, 'DAY');
RETURN day;
END;

DECLARE
A DATE;
day VARCHAR(10);
BEGIN
A:= :A;
day := weekday(A);
dbms_output.put_line('Weekday: '||day);
END;

//FUNCTION to return number of sailors in a given rating level

CREATE OR REPLACE FUNCTION sailcount


(low IN Sailors.Rating%TYPE, high IN Sailors.Rating%TYPE)
RETURN INT IS
cnt INT;
BEGIN
SELECT COUNT(*) INTO cnt FROM Sailors WHERE Rating BETWEEN low AND high;
RETURN cnt;
END sailcount;

DECLARE
L INT;
H INT;
cnt INT;
BEGIN
L := :L;
H := :H;
cnt:= sailcount(L,H);
dbms_output.put_line(cnt);
END;
CMR College Of Engineering & Technology
Dept Of CSE
//FUNCTION to return avg age of sailors in a given rating level
CREATE OR REPLACE FUNCTION avgage
(low IN Sailors.Rating%TYPE, high IN Sailors.Rating%TYPE)
RETURN INT IS
cnt INT;
BEGIN
SELECT AVG(Age) INTO cnt FROM Sailors WHERE Rating BETWEEN low AND high;
RETURN cnt;
END avgage;

DECLARE
L INT;
H INT;
cnt INT;
BEGIN
L := :L;
H := :H;
cnt:= avgage(L,H);
dbms_output.put_line(cnt);
END;

10. Usage of Cursors


1.Display the employee names and their salary for the accepted department number.

Solution

declare
cursor c1 is select * from emp where deptno= :D_NO;
rec emp%rowtype;
begin
open c1;
loop
fetch c1 into rec;
exit when c1%notfound;
dbms_output.put_line('Dept No= '||rec.deptno||' Emp name= '||rec.ename||' Salary='||rec.sal);
end loop;
close c1;
end;

2.Display the top N earners for an accepted department number.


Solution
DECLARE
dnum NUMBER(10) := :dept_number; -- Accept department number as input
n NUMBER(10) := :top_n; -- Accept the number N as input (e.g., top 5 earners)

CURSOR top_earners_cursor IS
select * from (select * from emp where deptno=dnum order by sal desc) where rownum<=n;
-- Variables to store employee details fetched by the cursor
CMR College Of Engineering & Technology
Dept Of CSE
name emp.ename%TYPE;
salary emp.sal%TYPE;

BEGIN
-- Open the cursor
OPEN top_earners_cursor;

-- Loop through the cursor and fetch each row


LOOP
-- Fetch the employee name and salary
FETCH top_earners_cursor INTO name, salary;

EXIT WHEN top_earners_cursor%NOTFOUND;

DBMS_OUTPUT.PUT_LINE('Employee: ' || name || ', Salary: ' || salary);


END LOOP;

-- Close the cursor after use


CLOSE top_earners_cursor;

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employees found for the given department.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END;
Q3 To write a Cursor to display the list of employees who are working as a Managers or Analyst.

Solution

declare
cursor c4 is select * from emp where job in('MANAGER','ANALYST');
rec emp%rowtype;
begin
open c4;
dbms_output.put_line('....LIST OF EMPLOYEES WHO ARE MANAGERS OR ANALYSTS');
loop
fetch c4 into rec;
exit when c4%notfound;
dbms_output.put_line( 'Emp name= '||rec.ename||' JOB='||rec.job);
end loop;
close c4;
end;

Q4. write a Cursor to find employee with given job and deptno.

solution

declare
CMR College Of Engineering & Technology
Dept Of CSE
dno number(10):= :Dept_No;
j varchar2(32):= :JOB;
cursor c5 is select * from emp where job=j and deptno=dno;
rec emp%rowtype;
begin
open c5;
dbms_output.put_line('....LIST OF EMPLOYEES ----');
loop
fetch c5 into rec;
exit when c5%notfound;
dbms_output.put_line( 'Emp name='||rec.ename||' JOB=' ||rec.job || ' Dept No= '||rec.deptno);
end loop;
close c5;
end;

Q5.Write a PL/SQL block using implicit cursor that will display message, the salaries of all the employees in the employee
table are updated

solution

DECLARE
cnt NUMBER(10) := 0;
BEGIN
UPDATE emp SET sal = sal* 1.1;

cnt:= SQL%ROWCOUNT;

IF cnt = 0 THEN
DBMS_OUTPUT.PUT_LINE('None of the salaries were updated.');
ELSE
DBMS_OUTPUT.PUT_LINE('Salaries for ' || cnt || ' employees are updated.');
END IF;

end;

11.Packages
Step 1:
create table cmrcet_emp(eid number(10) primary key,ename varchar2(32), dept varchar2(32));

Step 2:
CREATE OR REPLACE PACKAGE hr_package AS
PROCEDURE hire(emp_id NUMBER, emp_name VARCHAR2, emp_department VARCHAR2);
PROCEDURE fire(emp_id NUMBER);
END hr_package;

Step 3:
CMR College Of Engineering & Technology
Dept Of CSE
CREATE OR REPLACE PACKAGE BODY hr_package AS
PROCEDURE hire(emp_id NUMBER, emp_name VARCHAR2, emp_department VARCHAR2) IS
BEGIN
-- Insert employee data into the employees table
INSERT INTO cmrcet_emp VALUES (emp_id, emp_name, emp_department);

DBMS_OUTPUT.PUT_LINE('Employee ' || emp_name || ' hired successfully.');


EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('Error: Employee with ID ' || emp_id || ' already exists.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END hire;

PROCEDURE fire(emp_id NUMBER) IS


emp_name VARCHAR2(100);
BEGIN
-- Fetch employee name before deletion
SELECT ename INTO emp_name FROM cmrcet_emp WHERE eid = emp_id;

-- Delete employee from the employees table


DELETE FROM cmrcet_emp WHERE eid = emp_id;

DBMS_OUTPUT.PUT_LINE('Employee ' || emp_name || ' fired successfully.');


EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Error: Employee with ID ' || emp_id || ' does not exist.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END fire;

END hr_package;

Step 4:
begin
hr_package.hire(1,'vivekanand','CSE');
hr_package.fire(1);
end;
CMR College Of Engineering & Technology
Dept Of CSE

You might also like