0% found this document useful (0 votes)
54 views

DBMS PRACTICAL

The document outlines the creation and manipulation of various database schemas including Library, Employee, Movie, and College databases. It includes SQL commands for creating tables, inserting data, querying information, and implementing triggers and procedures. Additionally, it demonstrates how to manage relationships between tables using foreign keys and how to perform operations like updates and deletions.

Uploaded by

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

DBMS PRACTICAL

The document outlines the creation and manipulation of various database schemas including Library, Employee, Movie, and College databases. It includes SQL commands for creating tables, inserting data, querying information, and implementing triggers and procedures. Additionally, it demonstrates how to manage relationships between tables using foreign keys and how to perform operations like updates and deletions.

Uploaded by

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

1.

Consider the following schema for a Library Database:


BOOK (Book_id, Title, Publisher_Name, Pub_Year, No_of_copies)
BOOK_AUTHORS (Book_id, Author_Name)
PUBLISHER (Name, Address, Phone)

CREATE TABLE BOOK (

Book_id INT PRIMARY KEY,

Title VARCHAR(100),

Publisher_Name VARCHAR(50),

Pub_Year INT,

No_of_copies INT,

FOREIGN KEY (Publisher_Name) REFERENCES PUBLISHER(Name)

);

CREATE TABLE BOOK_AUTHORS (

Book_id INT,

Author_Name VARCHAR(100),

PRIMARY KEY (Book_id, Author_Name),

FOREIGN KEY (Book_id) REFERENCES BOOK(Book_id)

);

CREATE TABLE PUBLISHER (

Name VARCHAR(50) PRIMARY KEY,

Address VARCHAR(150),

Phone VARCHAR(20)

);

INSERT INTO PUBLISHER (Name, Address, Phone)


VALUES ('Tech Books Publishing', '123 Tech Street, City', '123-456-7890');

INSERT INTO PUBLISHER (Name, Address, Phone)

VALUES ('SQL Masters Publishing', '456 SQL Road, City', '987-654-3210');

INSERT INTO BOOK (Book_id, Title, Publisher_Name, Pub_Year, No_of_copies)

VALUES (1, 'Database Systems', 'Tech Books Publishing', 2020, 50);

INSERT INTO BOOK (Book_id, Title, Publisher_Name, Pub_Year, No_of_copies)

VALUES (2, 'Advanced SQL', 'SQL Masters Publishing', 2019, 30);

INSERT INTO BOOK_AUTHORS (Book_id, Author_Name)

VALUES (1, 'John Smith');

INSERT INTO BOOK_AUTHORS (Book_id, Author_Name)

VALUES (2, 'Jane Doe');

CREATED TABLES OUTPUT:

a) 100 Retrieve details of all books in the Book_id, title, name of publisher, authors
SELECT
B.Book_id,
B.Title,
B.Publisher_Name,
BA.Author_Name
FROM
BOOK B
JOIN BOOK_AUTHORS BA ON B.Book_id = BA.Book_id;

OUTPUT:

b) Get the particulars of borrowers who have borrowed more than 3 books, but from Jan
2017 to Jun2017.

CREATE TABLE BORROWERS (


borrower_id INT,
Book_id INT,
borrow_date DATE,
PRIMARY KEY (borrower_id, book_id)
);
INSERT INTO BORROWERS (borrower_id, Book_id, borrow_date) VALUES
(1, 1, TO_DATE('2017-01-05', 'YYYY-MM-DD')),
(1, 2, TO_DATE('2017-02-10', 'YYYY-MM-DD')),
(1, 3, TO_DATE('2017-03-15', 'YYYY-MM-DD')),
(1, 6, TO_DATE('2017-03-15', 'YYYY-MM-DD')),
(2, 4, TO_DATE('2017-04-20', 'YYYY-MM-DD')),
(2, 5, TO_DATE('2017-06-05', 'YYYY-MM-DD'));
SELECT borrower_id, COUNT(*) AS book_count
FROM BORROWERS
WHERE borrow_date BETWEEN '2017-01-01' AND '2017-06-30'
GROUP BY borrower_id
HAVING COUNT(*) > 3;

c) Delete a book in BOOK table. Update the contents of other tables to reflect this data
Manipulation operations.

DELETE FROM BOOK_AUTHORS WHERE Book_id = 1;


DELETE FROM BORROWERS WHERE Book_id = 1;
DELETE FROM BOOK WHERE Book_id = 1;

For checking:
SELECT*FROM BOOK;
SELECT*FROM BOOK_AUTHORS;
SELECT*FROM BORROWERS;
d) Create a view of all books and its number of copies that are currently available in the
Library.

CREATE VIEW Available_Books AS


SELECT Book_id, Title, No_of_copies
FROM BOOK
WHERE No_of_copies > 0;

SELECT * FROM Available_Books;

e) Write a Pl/SQL procedure to display the book details of particular author.


CREATE OR REPLACE PROCEDURE ShowBooksByAuthor(p_author IN VARCHAR2) IS
BEGIN
FOR b IN (
SELECT B.Book_id, B.Title
FROM BOOK B
JOIN BOOK_AUTHORS BA ON B.Book_id = BA.Book_id
WHERE BA.Author_Name = p_author
) LOOP
DBMS_OUTPUT.PUT_LINE('Book ID: ' || b.Book_id || ' | Title: ' || b.Title);
END LOOP;
END;
/
2. Create a table employee (S.No,Name,Desination,brach)

CREATE TABLE employee (


S_No INT PRIMARY KEY,
Name VARCHAR(50),
Designation VARCHAR(50),
Branch VARCHAR(50)
);

INSERT INTO employee (S_No, Name, Designation, Branch) VALUES (1, 'Alice', 'Manager',
'HR');
INSERT INTO employee (S_No, Name, Designation, Branch) VALUES (2, 'Bob', 'Developer',
'IT');
INSERT INTO employee (S_No, Name, Designation, Branch) VALUES (3, 'Charlie', 'Tester',
'QA');

a) Alter the table by adding a column salary

ALTER TABLE employee ADD salary NUMBER(10);

b) Copy the table employee as Emp

CREATE TABLE Emp AS SELECT * FROM employee;


SELECT* FROM employee;
SELECT * FROM Emp;

c) Delete 2nd row from the table

DELETE FROM employee


WHERE S_No = (
SELECT S_No FROM (
SELECT S_No, ROWNUM AS rn FROM (
SELECT S_No FROM employee ORDER BY S_No
)
) WHERE rn = 2
);

SELECT * FROM employee;

d) Drop the table

DROP TABLE employee;

e) Demonstrate the triggers for automatic updation.


CREATE OR REPLACE TRIGGER emp_salary_update
BEFORE UPDATE ON employee
FOR EACH ROW
WHEN (NEW.salary IS NULL)
BEGIN
:NEW.salary := 15000;
END;

CREATE OR REPLACE TRIGGER emp_salary_update


BEFORE UPDATE ON employee
FOR EACH ROW
BEGIN
IF :NEW.salary IS NULL THEN
:NEW.salary := 15000;
END IF;
END;
/

3. Create a table called Employee (Emp_no Emp_name, Emp_dept,Job ,Mgr ,Sal)

CREATE TABLE Employee (


Emp_no INT PRIMARY KEY,
Emp_name VARCHAR(50),
Emp_dept VARCHAR(50),
Job VARCHAR(50),
Mgr INT,
Sal NUMBER(10, 2)
);

INSERT INTO Employee (Emp_no, Emp_name, Emp_dept, Job, Mgr, Sal)


VALUES (1, 'Alice', 'HR', 'Manager', NULL, 30000);

INSERT INTO Employee (Emp_no, Emp_name, Emp_dept, Job, Mgr, Sal)


VALUES (2, 'Bob', 'IT', 'Developer', 1, 25000);

INSERT INTO Employee (Emp_no, Emp_name, Emp_dept, Job, Mgr, Sal)


VALUES (3, 'Charlie', 'IT', 'Tester', 1, 20000);

INSERT INTO Employee (Emp_no, Emp_name, Emp_dept, Job, Mgr, Sal)


VALUES (4, 'David', 'HR', 'Developer', 1, 15000);
a) By using the group by clause, display the Emp_name who belongs to Emp_dept=”xxx”
along with salary

SELECT Emp_name, Sal


FROM Employee
WHERE Emp_dept = 'IT'
GROUP BY Emp_name, Sal;

b) Display lowest paid employee details under each department

SELECT Emp_dept, MIN(Sal) AS Min_Salary


FROM Employee
GROUP BY Emp_dept;

c) List the employee names in descending order.

SELECT Emp_name FROM Employee ORDER BY Emp_name DESC;

d) Rename the column of Employee table using alter command


ALTER TABLE Employee RENAME COLUMN Emp_name TO Employee_Name;

e) Insert row in employee table using Triggers.

CREATE OR REPLACE TRIGGER emp_insert_trigger


BEFORE INSERT ON Employee
FOR EACH ROW
BEGIN
IF :NEW.Sal IS NULL THEN
:NEW.Sal := 10000;
END IF;
END;

4. Consider the following tables namely “DEPARTMENTS” and “EMPLOYEES” _no ,


Departments ( dept_ name , dept_location ), Employees ( emp_id , emp_name ,
emp_salary,dept_no).

CREATE TABLE DEPARTMENTS (


dept_no INT PRIMARY KEY,
dept_name VARCHAR(50),
dept_location VARCHAR(50)
);

INSERT INTO DEPARTMENTS (dept_no, dept_name, dept_location)


VALUES (1, 'HR', 'New York');

INSERT INTO DEPARTMENTS (dept_no, dept_name, dept_location)


VALUES (2, 'IT', 'San Francisco');

CREATE TABLE EMPLOYEES (


emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
emp_salary DECIMAL(10, 2),
dept_no INT,
FOREIGN KEY (dept_no) REFERENCES DEPARTMENTS(dept_no)
);

INSERT INTO EMPLOYEES (emp_id, emp_name, emp_salary, dept_no)


VALUES (1001, 'Alice', 55000, 1);

INSERT INTO EMPLOYEES (emp_id, emp_name, emp_salary, dept_no)


VALUES (1002, 'Bob', 60000, 2);

INSERT INTO EMPLOYEES (emp_id, emp_name, emp_salary, dept_no)


VALUES (1003, 'Charlie', 45000, 1);

a) Develop a query to grant some privileges of employees table into departments table

GRANT SELECT, UPDATE ON Employees TO Departments;


b) Develop a query to revoke all privileges of employees table from departments table

REVOKE ALL ON Employees FROM Departments;

c) Develop a query to revoke some privileges of employees table from departments table

REVOKE UPDATE ON Employees FROM Departments;

d) Write a query to implement the save point.

SAVEPOINT before_update;
ROLLBACK TO before_update;

e) Demonstrate the user defined procedure for the above employee database
CREATE OR REPLACE PROCEDURE Display_Employees AS
BEGIN
FOR rec IN (SELECT * FROM Employees) LOOP
DBMS_OUTPUT.PUT_LINE('ID: ' || rec.emp_id || ' Name: ' || rec.emp_name);
END LOOP;
END;

5. Create the following tables, Event (eventid, name, description,city) Participant (playerid,
name, eventid, gender, year) Prizes (prizeid, prize-money, eventid, rank,year) Winners
(prizeid, playerid)

a) Choose appropriate primary keys and foreign keys for the tables.

ALTER TABLE Event ADD PRIMARY KEY(eventid);


ALTER TABLE Participant ADD CONSTRAINT fk_event FOREIGN KEY(eventid)
REFERENCES Event(eventid);
ALTER TABLE Prizes ADD CONSTRAINT fk_prize_event FOREIGN KEY(eventid)
REFERENCES Event(eventid);
ALTER TABLE Winners ADD CONSTRAINT fk_prize FOREIGN KEY(prizeid)
REFERENCES Prizes(prizeid);
ALTER TABLE Winners ADD CONSTRAINT fk_player FOREIGN KEY(playerid)
REFERENCES Participant(playerid);

b) Playerid should contain at least one digit character.

ALTER TABLE Participant


ADD CONSTRAINT chk_playerid CHECK (REGEXP_LIKE(playerid, '.*[0-9].*'));

ALTER TABLE Participant


ADD CONSTRAINT check_playerid CHECK (REGEXP_LIKE(playerid, '.*\d.*'));

c) Retrieve the name of events where all prize winners are females

SELECT E.name
FROM Event E
JOIN Participant P ON E.eventid = P.eventid
JOIN Winners W ON P.playerid = W.playerid
GROUP BY E.eventid, E.name
HAVING COUNT(DISTINCT CASE WHEN gender = 'Female' THEN playerid END) =
COUNT(DISTINCT playerid);
SELECT E.name
FROM Event E
JOIN Prizes Pr ON E.eventid = Pr.eventid
JOIN Winners W ON Pr.prizeid = W.prizeid
JOIN Participant P ON W.playerid = P.playerid
GROUP BY E.eventid, E.name
HAVING COUNT(DISTINCT CASE WHEN P.gender = 'Female' THEN P.playerid END) =
COUNT(DISTINCT P.playerid);

d) Create a non-updatable view to retrieve the names of all participants who won 1st
prizes along with their event names

CREATE VIEW First_Prize_Winners AS


SELECT P.name AS Player_Name, E.name AS Event_Name
FROM Participant P
JOIN Winners W ON P.playerid = W.playerid
JOIN Prizes PR ON W.prizeid = PR.prizeid
JOIN Event E ON P.eventid = E.eventid
WHERE PR.rank = 1
WITH READ ONLY;

e) Write a trigger to make sure that for every new event created, 3 prizes are created in
prizes table. (1st prize - 1500, 2nd - 1000, 3rd 500)

CREATE OR REPLACE TRIGGER add_prizes_trigger


AFTER INSERT ON Event
FOR EACH ROW
BEGIN
INSERT INTO Prizes (prizeid, prize_money, eventid, rank, year)
VALUES (SEQ_PRIZEID.NEXTVAL, 1500, :NEW.eventid, 1, EXTRACT(YEAR FROM
SYSDATE));
INSERT INTO Prizes (prizeid, prize_money, eventid, rank, year)
VALUES (SEQ_PRIZEID.NEXTVAL, 1000, :NEW.eventid, 2, EXTRACT(YEAR FROM
SYSDATE));
INSERT INTO Prizes (prizeid, prize_money, eventid, rank, year)
VALUES (SEQ_PRIZEID.NEXTVAL, 500, :NEW.eventid, 3, EXTRACT(YEAR FROM
SYSDATE));
END;

6. Consider the schema for Movie Database:


ACTOR (Act_id, Act_Name, Act_Gender)
DIRECTOR (Dir_id , Dir_Name, Dir_Phone)
MOVIES (Mov_id , Mov_Title, Mov_Year, Mov_Lang, Dir_id)
MOVIE_CAST (Act_id , Mov_id , Role)

a) List the titles of all movies directed by ‘XXXX’.

SELECT Mov_Title
FROM MOVIES M
JOIN DIRECTOR D ON M.Dir_id = D.Dir_id
WHERE D.Dir_Name = 'XXXX';

b) Find the movie names where one or more actors acted in two or more movies.

SELECT M.Mov_Title
FROM MOVIES M
JOIN MOVIE_CAST MC ON M.Mov_id = MC.Mov_id
WHERE MC.Act_id IN (
SELECT Act_id
FROM MOVIE_CAST
GROUP BY Act_id
HAVING COUNT(DISTINCT Mov_id) >= 2
);

c) List all actors who acted in a movie before 2010 and also in a movie after 2015 (use
JOIN operation).

SELECT DISTINCT A.Act_Name


FROM ACTOR A
JOIN MOVIE_CAST MC1 ON A.Act_id = MC1.Act_id
JOIN MOVIES M1 ON MC1.Mov_id = M1.Mov_id
JOIN MOVIE_CAST MC2 ON A.Act_id = MC2.Act_id
JOIN MOVIES M2 ON MC2.Mov_id = M2.Mov_id
WHERE M1.Mov_Year < 2010 AND M2.Mov_Year > 2015;

d) Create a view of movies with a particular actor with director.

CREATE VIEW Actor_Movie_Director_View AS


SELECT A.Act_Name, M.Mov_Title, D.Dir_Name
FROM ACTOR A
JOIN MOVIE_CAST MC ON A.Act_id = MC.Act_id
JOIN MOVIES M ON MC.Mov_id = M.Mov_id
JOIN DIRECTOR D ON M.Dir_id = D.Dir_id;

e) Demonstrate the User defined function for the movie database.

CREATE OR REPLACE FUNCTION CountMoviesByDirector(dname VARCHAR2)


RETURN NUMBER IS
movie_count NUMBER;
BEGIN
SELECT COUNT(*) INTO movie_count
FROM MOVIES M JOIN DIRECTOR D ON M.Dir_id = D.Dir_id
WHERE D.Dir_Name = dname;
RETURN movie_count;
END;

7.Consider the schema for College Database:

STUDENT (RegNo , StudName, Address, Phone, Gender)

SUBJECT (Subcode , Title, Sem, Credits)

MARKS (RegNo, Subcode, Test1, Test2, Test3, Finalmark)

a) Compute the total number of male and female students in each semester and in each
section.

SELECT S.Sem, S.Section, St.Gender, COUNT(*) AS Total


FROM STUDENT St
JOIN SUBJECT S ON St.RegNo = S.RegNo
GROUP BY S.Sem, S.Section, St.Gender;

b) Calculate the Finalmark (average of best two test marks) and update the
corresponding table for all students.

UPDATE MARKS
SET Finalmark = (GREATEST(Test1 + Test2, Test1 + Test3, Test2 + Test3)) / 2;

c) Categorize students based on the following criterion:


If Finalmark = 81 to 100 then CAT = ‘Outstanding’ If Finalmark = 51 to 80 then CAT =
‘Average’ If Finalmark < 51 then CAT = ‘Weak

ALTER TABLE MARKS ADD CAT VARCHAR2(20);


UPDATE MARKS
SET CAT = CASE
WHEN Finalmark BETWEEN 81 AND 100 THEN 'Outstanding'
WHEN Finalmark BETWEEN 51 AND 80 THEN 'Average'
ELSE 'Weak'
END;

d) Create a view of Test3 marks of particular student in all subjects.

CREATE VIEW Student_Test3_View AS


SELECT Subcode, Test3
FROM MARKS
WHERE RegNo = 'XXXX';

e) Demonstrate the procedure for the above Database.

CREATE OR REPLACE PROCEDURE DisplayStudentMarks(reg IN VARCHAR2) IS


BEGIN
FOR rec IN (SELECT * FROM MARKS WHERE RegNo = reg) LOOP
DBMS_OUTPUT.PUT_LINE('Subcode: ' || rec.Subcode || ', Finalmark: ' || rec.Finalmark);
END LOOP;
END;

8.Create table as Bank ( S.No,Cust_Name, Acc_No, Balance, Branch)

a) Select with where clause.

SELECT * FROM BANK WHERE Branch = 'Chennai';

b) Select with comparison operator.

SELECT * FROM BANK WHERE Balance > 10000;

c) Update the balance in the second row.

UPDATE BANK
SET Balance = 5000
WHERE ROWID IN (SELECT ROWID FROM BANK WHERE ROWNUM = 2);

d) Select with between in the field balance.


SELECT * FROM BANK WHERE Balance BETWEEN 5000 AND 15000;

e) Write a trigger when balance is below 1000.

CREATE OR REPLACE TRIGGER check_balance


BEFORE UPDATE OR INSERT ON BANK
FOR EACH ROW
BEGIN
IF :NEW.Balance < 1000 THEN
RAISE_APPLICATION_ERROR(-20001, 'Balance too low!');
END IF;
END;

9.Create a table Account (Account_No, Cust_Name, Branch_Name, Account_Balance,


Account_Type) Select an appropriate primary key.

a) Display the Cust_Name and Account_No of the customers of "Branch = XXXXX".

SELECT Cust_Name, Account_No


FROM ACCOUNT
WHERE Branch_Name = 'XXXXX';
OUTPUT:

Cust_Name Account_No

Alice 101

David 104

b) Display the names and account types of all the customers whose account balance is
more than 10,000.

SELECT Cust_Name, Account_Type


FROM ACCOUNT
WHERE Account_Balance > 10000;

OUTPUT:

Cust_Name Account_Type
Alice Savings

Charlie Savings

Eva Savings

c) Add column Cust_Date_of Birth in the ACCOUNT table.

ALTER TABLE ACCOUNT ADD Cust_Date_of_Birth DATE;

d) Display Account_No, Cust_Name and Branch of all the customers whose account
balance is less than 1,000.

SELECT Account_No, Cust_Name, Branch_Name


FROM ACCOUNT
WHERE Account_Balance < 1000;

Output:

Account_No Cust_Name Branch_Name

102 Bob Mumbai

104 David Chennai

e) Write a procedure for the above Database.

CREATE OR REPLACE PROCEDURE DisplayLowBalanceAccounts IS


BEGIN
FOR rec IN (SELECT * FROM ACCOUNT WHERE Account_Balance < 1000) LOOP
DBMS_OUTPUT.PUT_LINE('Account: ' || rec.Account_No || ', Name: ' || rec.Cust_Name);
END LOOP;
END;
Account: 102, Name: Bob
Account: 104, Name: David
10. Create the tables CUSTOMER (C_ID, Name, Address, City, Mobile_No) and ORDER
(C_ID, P_ID, P_Name, P_COST)

C_ID Name Address City Mobile_No Email_id

1 Alice 123 Street A Delhi 9876543210 (null)

2 Bob 456 Street B Mumbai 9123456780 (null)

3 Charlie 789 Street Delhi 9988776655 (null)


C

ORDER Table
C_ID P_ID P_Name P_COST

1 101 Laptop 55000

1 102 Mouse 400

2 103 Keyboard 1200

3 104 Monitor 950

3 105 Printer 1500

a) List the names and addresses of all the customers who have ordered products of
costmore than 500.

SELECT DISTINCT C.Name, C.Address


FROM CUSTOMER C
JOIN ORDER O ON C.C_ID = O.C_ID
WHERE O.P_COST > 500;

OUTPUT:
Name Address

Alice 123 Street A

Bob 456 Street B

Charlie 789 Street C

b) List the names of all the products ordered whose cost is 1,000 or more.
SELECT DISTINCT P_Name
FROM ORDER
WHERE P_COST >= 1000;
OUTPUT:
P_Name

Laptop

Keyboard

Printer

c) List the product names which are ordered by customers of "City = Delhi".

SELECT DISTINCT O.P_Name


FROM CUSTOMER C
JOIN ORDER O ON C.C_ID = O.C_ID
WHERE C.City = 'Delhi';

OUTPUT:

P_Name

Laptop

Mouse

Monitor

Printer

d) Add column "Email_id" in the CUSTOMER table.

ALTER TABLE CUSTOMER ADD Email_id VARCHAR2(50);

OUTPUT:

C_ID Name Address City Mobile_No Email_id


e) Demonstrate the user defined function for the above tables.

CREATE OR REPLACE FUNCTION TotalOrderCost(cid NUMBER)


RETURN NUMBER IS
total_cost NUMBER;
BEGIN
SELECT SUM(P_COST) INTO total_cost
FROM ORDER
WHERE C_ID = cid;
RETURN total_cost;
END;

OUTPUT:
Total Cost for Alice: 55400
(Laptop: 55000 + Mouse: 400 = 55400)

11. Create the tables SALESMAN (Salesman_id, Name, City, Commission), CUSTOMER
(Customer_id, Cust_Name, City, Grade,Salesman_id), ORDERS (Ord_No, Purchase_Amt,
Ord_Date, Customer_id, Salesman_id)

SALESMAN

CREATE TABLE SALESMAN (


Salesman_id NUMBER PRIMARY KEY,
Name VARCHAR2(50),
City VARCHAR2(50),
Commission NUMBER(5,2)
);

CUSTOMER

CREATE TABLE CUSTOMER (


Customer_id NUMBER PRIMARY KEY,
Cust_Name VARCHAR2(50),
City VARCHAR2(50),
Grade NUMBER,
Salesman_id NUMBER,
FOREIGN KEY (Salesman_id) REFERENCES SALESMAN(Salesman_id)
);

ORDERS

CREATE TABLE ORDERS (


Ord_No NUMBER PRIMARY KEY,
Purchase_Amt NUMBER(10,2),
Ord_Date DATE,
Customer_id NUMBER,
Salesman_id NUMBER,
FOREIGN KEY (Customer_id) REFERENCES CUSTOMER(Customer_id),
FOREIGN KEY (Salesman_id) REFERENCES SALESMAN(Salesman_id)
);

Insert into SALESMAN


INSERT INTO SALESMAN VALUES (1000, 'Ravi', 'Chennai', 0.10);
INSERT INTO SALESMAN VALUES (1001, 'Priya', 'Madurai', 0.12);
INSERT INTO SALESMAN VALUES (1002, 'Arun', 'Chennai', 0.15);

Insert into CUSTOMER


INSERT INTO CUSTOMER VALUES (2000, 'Ajay', 'Chennai', 1, 1000);
INSERT INTO CUSTOMER VALUES (2001, 'Divya', 'Madurai', 2, 1001);
INSERT INTO CUSTOMER VALUES (2002, 'Rahul', 'Chennai', 1, 1000);
INSERT INTO CUSTOMER VALUES (2003, 'Sneha', 'Trichy', 3, 1002);

Insert into ORDERS


INSERT INTO ORDERS VALUES (3000, 5000, TO_DATE('2023-11-01', 'YYYY-MM-DD'),
2000, 1000);
INSERT INTO ORDERS VALUES (3001, 7000, TO_DATE('2023-11-02', 'YYYY-MM-DD'),
2001, 1001);
INSERT INTO ORDERS VALUES (3002, 4500, TO_DATE('2023-11-05', 'YYYY-MM-DD'),
2002, 1000);
INSERT INTO ORDERS VALUES (3003, 8500, TO_DATE('2023-11-08', 'YYYY-MM-DD'),
2003, 1002)
a) Find the name and numbers of all salesmen who had more than one customer.

SELECT Salesman_id
FROM CUSTOMER
GROUP BY Salesman_id
HAVING COUNT(*) > 1;

SALESMAN_ID
-----------
1000

b) List all salesmen and indicate those who have and don’t have customers in their cities
(Use UNION operation.)

SELECT Name, 'Has Customer' AS Status


FROM SALESMAN
WHERE Salesman_id IN (
SELECT Salesman_id
FROM CUSTOMER
WHERE CUSTOMER.City = SALESMAN.City
)

UNION

SELECT Name, 'No Customer' AS Status


FROM SALESMAN
WHERE Salesman_id NOT IN (
SELECT Salesman_id
FROM CUSTOMER
WHERE CUSTOMER.City = SALESMAN.City
);

NAME STATUS
-------------------------------------------------- -----------
Arun No Customer

c) Create a view that finds the salesman who has the customer with the highest order of a
day.

CREATE VIEW Top_Order_View AS


SELECT s.Name, c.Cust_Name, o.Purchase_Amt, o.Ord_Date
FROM ORDERS o
JOIN SALESMAN s ON o.Salesman_id = s.Salesman_id
JOIN CUSTOMER c ON o.Customer_id = c.Customer_id
WHERE o.Purchase_Amt = (
SELECT MAX(Purchase_Amt)
FROM ORDERS
WHERE Ord_Date = o.Ord_Date
);

View created.

d) Perform the DELETE operation by removing salesman with id 1000. All his orders must
also be deleted.

SQL> DELETE FROM ORDERS


2 WHERE Salesman_id = 1000;

0 rows deleted.

SQL> DELETE FROM CUSTOMER


2 WHERE Salesman_id = 1000;

2 rows deleted.

SQL> DELETE FROM SALESMAN


2 WHERE Salesman_id = 1000;

1 row deleted.

e) Demonstrate the Triggers for the above table.

CREATE OR REPLACE TRIGGER del_orders


BEFORE DELETE ON SALESMAN
FOR EACH ROW
BEGIN
DELETE FROM ORDERS
WHERE Salesman_id = :OLD.Salesman_id;
END;
/
Trigger created.
12. a) Create a bank database table, add constraints (primary key, check), insert rows,
update and delete rows using DDL and DML commands.

Create BANK table with constraints


CREATE TABLE BANK (
Acc_No INT PRIMARY KEY,
Cust_Name VARCHAR(50),
Branch_Name VARCHAR(50),
Balance DECIMAL(10,2) CHECK (Balance >= 0)
);
Table created.

Insert sample rows


INSERT INTO BANK VALUES (101, 'Ravi', 'Chennai', 500000);
INSERT INTO BANK VALUES (102, 'Priya', 'Madurai', 1200000);
INSERT INTO BANK VALUES (103, 'Anil', 'Trichy', 800000);

Update a row
UPDATE BANK
SET Balance = 600000
WHERE Acc_No = 101;
1 row updated.

Delete a row
DELETE FROM BANK
WHERE Acc_No = 103;

1 row deleted.

b) Create a PL SQL program that uses the where clause and having clause to retrieve
above 10 lakhs depositor details.

SET SERVEROUTPUT ON;

BEGIN
FOR rec IN (
SELECT Cust_Name, SUM(Balance) AS Total_Balance
FROM BANK
GROUP BY Cust_Name
HAVING SUM(Balance) > 1000000
)
LOOP
DBMS_OUTPUT.PUT_LINE('Name: ' || rec.Cust_Name || ' | Balance: ' || rec.Total_Balance);
END LOOP;
END;
/
Name: Priya | Balance: 1200000
PL/SQL procedure successfully completed.

13. a) Create a set of tables for cargo service database, add foreign key constraints and
incorporate referential integrity.

Create CUSTOMER table


CREATE TABLE CUSTOME (
Cust_ID INT PRIMARY KEY,
Cust_Name VARCHAR(50),
Phone VARCHAR(15)
);
Table created.

Create CARGO table


CREATE TABLE CARGO (
Cargo_ID INT PRIMARY KEY,
Description VARCHAR(100),
Weight DECIMAL(6,2),
Cust_ID INT,
FOREIGN KEY (Cust_ID) REFERENCES CUSTOME(Cust_ID)
);
Table created.

Create BOOKING table


CREATE TABLE BOOKING (
Booking_ID INT PRIMARY KEY,
Cargo_ID INT,
Booking_Date DATE,
Status VARCHAR(20),
FOREIGN KEY (Cargo_ID) REFERENCES CARGO(Cargo_ID)
);
Table created.

b) Create PL SQL triggers for cargo booking and cancellation system.

CREATE OR REPLACE TRIGGER after_booking


AFTER INSERT ON BOOKING
FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('Booking Done for Cargo ID: ' || :NEW.Cargo_ID);
END;
/
Trigger created.

CREATE OR REPLACE TRIGGER cancel_booking


BEFORE DELETE ON BOOKING
FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('Booking Cancelled for Cargo ID: ' || :OLD.Cargo_ID);
END;
/
Trigger created.

Sample Insert for Testing


-- Insert a customer
INSERT INTO CUSTOME VALUES (1, 'Rahul', '9876543210');

-- Insert a cargo for that customer


INSERT INTO CARGO VALUES (100, 'Electronics', 250.50, 1);

-- Book the cargo


INSERT INTO BOOKING VALUES (5001, 100, SYSDATE, 'Booked');
14. a) Create a query that uses a where clause to provide all information about books
linked to "Distributed Database."
CREATE TABLE BOO (
Book_id INT PRIMARY KEY,
Title VARCHAR(100),
Publisher_Name VARCHAR(50),
Pub_Year INT,
No_of_copies INT
);
Table created.

INSERT INTO BOO VALUES (1, 'Distributed Database', 'Pearson', 2022, 5);
1 row created.

INSERT INTO BOO VALUES (2, 'Operating Systems', 'McGraw Hill', 2021, 3);
1 row created.

INSERT INTO BOO VALUES (3, 'Distributed Database Systems', 'Oxford', 2023, 7);

1 row created.
SELECT *
FROM BOO
WHERE Title LIKE '%Distributed Database%';
b) Write a procedure to insert books details in library management system after
purchasing books.

Assume the BOOK table is like this:


CREATE TABLE BO (
Book_id INT PRIMARY KEY,
Title VARCHAR(100),
Publisher_Name VARCHAR(50),
Pub_Year INT,
No_of_copies INT
);
Table created.

Procedure to insert new book:

CREATE OR REPLACE PROCEDURE InsertBook(


p_id IN INT,
p_title IN VARCHAR,
p_pub IN VARCHAR,
p_year IN INT,
p_copies IN INT
)
IS
BEGIN
INSERT INTO BO(Book_id, Title, Publisher_Name, Pub_Year, No_of_copies)
VALUES(p_id, p_title, p_pub, p_year, p_copies);

DBMS_OUTPUT.PUT_LINE('Book inserted successfully: ' || p_title);


END;
/
Procedure created.

15. a) Create a Product, Sales and purchase table using DDL and DML commands

Create PRODUCT Table


CREATE TABLE PRODUC (
Product_ID INT PRIMARY KEY,
Product_Name VARCHAR(50),
Price DECIMAL(8,2)
);
Table created.

Create SALES Table


CREATE TABLE SALE (
Sale_ID INT PRIMARY KEY,
Product_ID INT,
Sale_Date DATE,
Quantity INT,
FOREIGN KEY (Product_ID) REFERENCES PRODUC(Product_ID)
);
Table created.

Create PURCHASE Table


CREATE TABLE PURCHSE (
Purchase_ID INT PRIMARY KEY,
Product_ID INT,
Purchase_Date DATE,
Quantity INT,
FOREIGN KEY (Product_ID) REFERENCES PRODUC(Product_ID)
);
Table created.

Insert Sample Record (DML)


INSERT INTO PRODUC VALUES (1, 'Pen', 10.50); 1 row created.
INSERT INTO SALE VALUES (101, 1, SYSDATE, 5); 1 row created.
INSERT INTO PURCHSE VALUES (201, 1, SYSDATE, 10); 1 row created.

b) Create a procedure to add 20 records to each table in the database mentioned above.

Simple PL/SQL Procedure:


CREATE OR REPLACE PROCEDURE Insert20Records IS
BEGIN
FOR i IN 1..20 LOOP
-- Product table
INSERT INTO PRODUC VALUES (i, 'Product_' || i, 10 * i);

-- Sales table
INSERT INTO SALE VALUES (100 + i, i, SYSDATE, i + 2);

-- Purchase table
INSERT INTO PURCHSE VALUES (200 + i, i, SYSDATE, i + 5);
END LOOP;

DBMS_OUTPUT.PUT_LINE('20 Records inserted in all tables.');


END;
/
Procedure created.

16. a) Using DDL and DML commands, create the employee_personal, Salary, and
Department tables. In addition, determine the minimum, maximum, total, and average
salaries in the database mentioned above.

employee_personal table (DDL)


CREATE TABLE employee_personal (
Emp_ID INT PRIMARY KEY,
Emp_Name VARCHAR(50),
Dept_ID INT
);
Table created.

department table (DDL)


CREATE TABLE department (
Dept_ID INT PRIMARY KEY,
Dept_Name VARCHAR(50)
);
Table created.

salary table (DDL)

CREATE TABLE salary (


Emp_ID INT PRIMARY KEY,
Basic_Salary DECIMAL(10,2),
FOREIGN KEY (Emp_ID) REFERENCES employee_personal(Emp_ID)
);
Table created.

Sample DML Inserts:


INSERT INTO department VALUES (1, 'HR'); 1 row created.
INSERT INTO employee_personal VALUES (101, 'Anita', 1); 1 row created.
INSERT INTO salary VALUES (101, 30000); 1 row created.
Find MIN, MAX, TOTAL, AVERAGE Salary:
SELECT MIN(Basic_Salary) AS Min_Salary,
MAX(Basic_Salary) AS Max_Salary,
SUM(Basic_Salary) AS Total_Salary,
AVG(Basic_Salary) AS Avg_Salary
FROM salary;

b) Create a user-defined function to update an employee's salary when they receive


incentives.

SQL> CREATE OR REPLACE FUNCTION AddBonus (


2 Emp_ID IN NUMBER,
3 Bonus IN NUMBER
4 ) RETURN NUMBER IS
5 New_Salary NUMBER;
6 BEGIN
7 -- Update salary
8 UPDATE EMPLOYEES
9 SET SALARY = SALARY + Bonus
10 WHERE EMP_ID = Emp_ID;
11
12 -- Get the updated salary
13 SELECT SALARY INTO New_Salary
14 FROM EMPLOYEES
15 WHERE EMP_ID = Emp_ID;
16
17 RETURN New_Salary;
18 END;
19 /

Function created.

17. a) Create an online purchase database using DDL and DML commands. Use sub
queries to present the information about the items you've purchased.

Create Tables
CREATE TABLE Ite(
Item_ID INT PRIMARY KEY,
Item_Name VARCHAR(50),
Price DECIMAL(10,2),
Stock INT
);
Table created.

CREATE TABLE Purchas(


Purchase_ID INT PRIMARY KEY,
Item_ID INT,
Quantity INT,
Purchase_Date DATE,
FOREIGN KEY (Item_ID) REFERENCES Ite(Item_ID)
);
Table created.

Insert Sample Data (DML)


INSERT INTO Ite VALUES (1, 'Laptop', 60000, 10); 1 row created.
INSERT INTO Ite VALUES (2, 'Mouse', 500, 30); 1 row created.
INSERT INTO Ite VALUES (3, 'Keyboard', 1000, 20); 1 row created.

INSERT INTO Purchas VALUES (101, 1, 2, SYSDATE); 1 row created.


INSERT INTO Purchas VALUES (102, 2, 1, SYSDATE); 1 row created.

Subquery – Show items you purchased


SELECT Item_Name, Price
FROM Ite
WHERE Item_ID IN (
SELECT Item_ID FROM Purchas
);

b) Write PL SQL Triggers to display available items after a successful purchase and also
display the available items before purchasing.

CREATE OR REPLACE TRIGGER update_stock


BEFORE INSERT ON Purchas
FOR EACH ROW
DECLARE
stock_before INT;
stock_after INT;
BEGIN
SELECT Stock INTO stock_before
FROM Ite
WHERE Item_ID = :NEW.Item_ID;

DBMS_OUTPUT.PUT_LINE('Stock Before: ' || stock_before);

UPDATE Ite
SET Stock = Stock - :NEW.Quantity
WHERE Item_ID = :NEW.Item_ID;

SELECT Stock INTO stock_after


FROM Ite
WHERE Item_ID = :NEW.Item_ID;

DBMS_OUTPUT.PUT_LINE('Stock After: ' || stock_after);


END;
/
Trigger created.

Example Purchase Insertion (to trigger the stock update)


INSERT INTO Purchase VALUES (103, 3, 2, SYSDATE);
1 row created.

18. a) Create Omni bus reservation database using DDL and DML commands and also
display the results after applying join operation.

Create Tables
CREATE TABLE Bus (
Bus_ID INT PRIMARY KEY,
Bus_Name VARCHAR(50),
Total_Seats INT
);
Table created.

CREATE TABLE Passenger (


Passenger_ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT
);
Table created.

CREATE TABLE Bookin (


Booking_ID INT PRIMARY KEY,
Bus_ID INT,
Passenger_ID INT,
Seats_Booked INT,
Booking_Date DATE,
FOREIGN KEY (Bus_ID) REFERENCES Bus(Bus_ID),
FOREIGN KEY (Passenger_ID) REFERENCES Passenger(Passenger_ID)
);
Table created.

Insert Sample Data


INSERT INTO Bus VALUES (1, 'Omni Express', 40); 1 row created.
INSERT INTO Bus VALUES (2, 'City Rider', 35); 1 row created.

INSERT INTO Passenger VALUES (101, 'Aarav', 22); 1 row created.


INSERT INTO Passenger VALUES (102, 'Diya', 28); 1 row created.

INSERT INTO Bookin VALUES (201, 1, 101, 2, SYSDATE); 1 row created.


INSERT INTO Bookin VALUES (202, 2, 102, 3, SYSDATE); 1 row created.

JOIN to Display Reservation Details


SELECT
B.Booking_ID, P.Name, Bus.Bus_Name, B.Seats_Booked, B.Booking_Date
FROM
Bookin B
JOIN
Passenger P ON B.Passenger_ID = P.Passenger_ID
JOIN
Bus ON B.Bus_ID = Bus.Bus_ID;
b) Write a procedure to avail reduction in booking of Omni bus.

CREATE OR REPLACE PROCEDURE ApplyDiscount (


p_BookingID IN INT
) IS
v_Seats INT;
v_Total DECIMAL;
v_Final DECIMAL;
BEGIN
SELECT Seats_Booked INTO v_Seats
FROM Bookin
WHERE Booking_ID = p_BookingID;

v_Total := v_Seats * 500;


v_Final := v_Total - (v_Seats * 50);

DBMS_OUTPUT.PUT_LINE('Total Amount: ₹' || v_Total);


DBMS_OUTPUT.PUT_LINE('Final Amount: ₹' || v_Final);
END;
/
Procedure created.

19. Create a database for a scooter manufacturing company and use the having clause to
display the scooter models based on price.

Create Tables for Scooter Manufacturing


CREATE TABLE Scooter (
Scooter_ID INT PRIMARY KEY,
Scooter_Model VARCHAR(50),
Price DECIMAL(10,2)
);
Table created.
CREATE TABLE Manufacturer (
Manufacturer_ID INT PRIMARY KEY,
Manufacturer_Name VARCHAR(50),
Location VARCHAR(50)
);
Table created.

CREATE TABLE Scooter_Manufacturer (


Scooter_ID INT,
Manufacturer_ID INT,
FOREIGN KEY (Scooter_ID) REFERENCES Scooter(Scooter_ID),
FOREIGN KEY (Manufacturer_ID) REFERENCES Manufacturer(Manufacturer_ID)
);
Table created.

Insert Sample Data

INSERT INTO Scooter VALUES (1, 'ScooterA', 25000); 1 row created.


INSERT INTO Scooter VALUES (2, 'ScooterB', 30000); 1 row created.
INSERT INTO Scooter VALUES (3, 'ScooterC', 20000); 1 row created.
INSERT INTO Scooter VALUES (4, 'ScooterD', 40000); 1 row created.

INSERT INTO Manufacturer VALUES (1, 'ManufacturerX', 'New York'); 1 row created.
INSERT INTO Manufacturer VALUES (2, 'ManufacturerY', 'Los Angeles'); 1 row created.

INSERT INTO Scooter_Manufacturer VALUES (1, 1); 1 row created.


INSERT INTO Scooter_Manufacturer VALUES (2, 2); 1 row created.
INSERT INTO Scooter_Manufacturer VALUES (3, 1); 1 row created.
INSERT INTO Scooter_Manufacturer VALUES (4, 2); 1 row created.

Use HAVING Clause to Display Scooters Based on Price


SELECT Scooter_Model, Price
FROM Scooter
GROUP BY Scooter_Model, Price
HAVING Price > 25000;
b) Write a procedure to insert and update the records in the above database.

CREATE OR REPLACE PROCEDURE AddOrUpdateScooter (


id IN NUMBER,
model IN VARCHAR2,
price IN NUMBER,
manu_id IN NUMBER
) IS
BEGIN
BEGIN
INSERT INTO Scooter (Scooter_ID, Scooter_Model, Price)
VALUES (id, model, price);
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
UPDATE Scooter
SET Scooter_Model = model, Price = price
WHERE Scooter_ID = id;
END;

INSERT INTO Scooter_Manufacturer (Scooter_ID, Manufacturer_ID)


VALUES (id, manu_id);

COMMIT;
END;
/

Procedure created.

20. a) Create and insert records in the flight and passenger tables, and then use various
join operations to display the records.

Create Tables for Flight and Passenger

CREATE TABLE Flight (


Flight_ID INT PRIMARY KEY,
Flight_Name VARCHAR(50),
Destination VARCHAR(50)
);
Table created.
CREATE TABLE Passenge(
Passenger_ID INT PRIMARY KEY,
Passenger_Name VARCHAR(50),
Flight_ID INT,
FOREIGN KEY (Flight_ID) REFERENCES Flight(Flight_ID)
);
Table created.

Insert Sample Data


INSERT INTO Flight VALUES (1, 'FlightA', 'Paris'); 1 row created.
INSERT INTO Flight VALUES (2, 'FlightB', 'London'); 1 row created.

INSERT INTO Passenge VALUES (101, 'John', 1); 1 row created.


INSERT INTO Passenge VALUES (102, 'Emma', 2); 1 row created.
INSERT INTO Passenge VALUES (103, 'Sophia', 1); 1 row created.

Use JOIN to Display Flight and Passenger Records


SELECT Passenge.Passenger_Name, Flight.Flight_Name, Flight.Destination
FROM Passenge
JOIN Flight ON Passenge.Flight_ID = Flight.Flight_ID;

b) Write a procedure to display month name while passing the month as number
parameter. (Example: if pass parameter as 1 it should display as January.)

CREATE OR REPLACE PROCEDURE Display_Month_Name (


p_Month_Num IN INT
) IS
v_Month_Name VARCHAR(20);
BEGIN
CASE p_Month_Num
WHEN 1 THEN v_Month_Name := 'January';
WHEN 2 THEN v_Month_Name := 'February';
WHEN 3 THEN v_Month_Name := 'March';
WHEN 4 THEN v_Month_Name := 'April';
WHEN 5 THEN v_Month_Name := 'May';
WHEN 6 THEN v_Month_Name := 'June';
WHEN 7 THEN v_Month_Name := 'July';
WHEN 8 THEN v_Month_Name := 'August';
WHEN 9 THEN v_Month_Name := 'September';
WHEN 10 THEN v_Month_Name := 'October';
WHEN 11 THEN v_Month_Name := 'November';
WHEN 12 THEN v_Month_Name := 'December';
ELSE v_Month_Name := 'Invalid Month';
END CASE;

DBMS_OUTPUT.PUT_LINE('Month: ' || v_Month_Name);


END;
/
Procedure created.

21. a) Create a student database table, add constraints (primary key, check), insert rows,
update and delete rows using DDL and DML commands.

Create Student Table with Constraints


CREATE TABLE Student (
Student_ID INT PRIMARY KEY,
Student_Name VARCHAR(50) NOT NULL,
Age INT CHECK (Age >= 18 AND Age <= 100),
Marks INT CHECK (Marks >= 0 AND Marks <= 100)
);

Insert Sample Data


INSERT INTO Student VALUES (1, 'John Doe', 20, 85);
INSERT INTO Student VALUES (2, 'Jane Smith', 22, 90);
INSERT INTO Student VALUES (3, 'Emily Johnson', 19, 30);
INSERT INTO Student VALUES (4, 'Michael Brown', 21, 60);

Update a Row (Update Marks)


UPDATE Student
SET Marks = 95
WHERE Student_ID = 2;

Delete a Row (Delete a Student)


DELETE FROM Student
WHERE Student_ID = 3;

b) Create a PL SQL program that uses the where clause to apply the moderation strategy
to those who all have more than 30 marks.

PL SQL Program for Applying Moderation Strategy

CREATE OR REPLACE PROCEDURE Apply_Moderation AS


BEGIN
UPDATE Student
SET Marks = Marks + 5
WHERE Marks > 30;

COMMIT;
DBMS_OUTPUT.PUT_LINE('Moderation applied to students with more than 30 marks.');
END;
/

22. a) Create a set of tables for Bus reservation database, add foreign key constraints and
incorporate referential integrity.

Create Tables for Bus Reservation


CREATE TABLE Bus (
Bus_ID INT PRIMARY KEY,
Bus_Name VARCHAR(50),
Seats_Available INT CHECK (Seats_Available > 0)
);

CREATE TABLE Passenger (


Passenger_ID INT PRIMARY KEY,
Passenger_Name VARCHAR(50),
Bus_ID INT,
FOREIGN KEY (Bus_ID) REFERENCES Bus(Bus_ID)
);

CREATE TABLE Reservation (


Reservation_ID INT PRIMARY KEY,
Passenger_ID INT,
Bus_ID INT,
Reservation_Date DATE,
FOREIGN KEY (Passenger_ID) REFERENCES Passenger(Passenger_ID),
FOREIGN KEY (Bus_ID) REFERENCES Bus(Bus_ID)
);

Insert Sample Data


INSERT INTO Bus VALUES (1, 'Bus A', 50);
INSERT INTO Bus VALUES (2, 'Bus B', 40);

INSERT INTO Passenger VALUES (101, 'Alice', 1);


INSERT INTO Passenger VALUES (102, 'Bob', 2);

INSERT INTO Reservation VALUES (1001, 101, 1, SYSDATE);


INSERT INTO Reservation VALUES (1002, 102, 2, SYSDATE);

b) Create PL SQL triggers for bus reservation system cancellation and reservation actions.

Trigger for Bus Reservation

CREATE OR REPLACE TRIGGER Reservation_Trigger


AFTER INSERT ON Reservation
FOR EACH ROW
BEGIN
UPDATE Bus
SET Seats_Available = Seats_Available - 1
WHERE Bus_ID = :NEW.Bus_ID;
END;
/
Trigger for Bus Cancellation
CREATE OR REPLACE TRIGGER Cancellation_Trigger
AFTER DELETE ON Reservation
FOR EACH ROW
BEGIN
UPDATE Bus
SET Seats_Available = Seats_Available + 1
WHERE Bus_ID = :OLD.Bus_ID;
END;
/
23. a) Create a query that uses a where clause to provide all information about books
linked to "Machine Learning."

Query to Retrieve All Information About Books Linked to "Machine Learning"

SELECT *
FROM Books
WHERE Title LIKE '%Machine Learning%';

b) Write a procedure to update books details in library management system after


purchasing books.

PL SQL Procedure to Update Book Details

CREATE OR REPLACE PROCEDURE Update_Book_Details (


p_Book_ID IN INT,
p_New_Title IN VARCHAR,
p_New_Publisher IN VARCHAR,
p_New_Year IN INT,
p_New_Copies IN INT
) IS
BEGIN
UPDATE Books
SET Title = p_New_Title,
Publisher_Name = p_New_Publisher,
Pub_Year = p_New_Year,
No_of_copies = p_New_Copies
WHERE Book_ID = p_Book_ID;

COMMIT;
DBMS_OUTPUT.PUT_LINE('Book details updated successfully.');
END;
/

27. a) Create wedding hall reservation database using DDL and DML commands and also
display the results after applying join operation.

Create Tables for Wedding Hall Reservation

CREATE TABLE Wedding_Hall (


Hall_ID INT PRIMARY KEY,
Hall_Name VARCHAR(50),
Capacity INT
);

CREATE TABLE Customer (


Customer_ID INT PRIMARY KEY,
Customer_Name VARCHAR(50),
Address VARCHAR(100)
);

CREATE TABLE Reservation (


Reservation_ID INT PRIMARY KEY,
Hall_ID INT,
Customer_ID INT,
Reservation_Date DATE,
FOREIGN KEY (Hall_ID) REFERENCES Wedding_Hall(Hall_ID),
FOREIGN KEY (Customer_ID) REFERENCES Customer(Customer_ID)
);

Insert Sample Data


INSERT INTO Wedding_Hall VALUES (1, 'Grand Hall', 200);
INSERT INTO Wedding_Hall VALUES (2, 'Royal Hall', 150);

INSERT INTO Customer VALUES (1, 'John Doe', '123 Elm St');
INSERT INTO Customer VALUES (2, 'Jane Smith', '456 Oak St');

INSERT INTO Reservation VALUES (1, 1, 1, SYSDATE);


INSERT INTO Reservation VALUES (2, 2, 2, SYSDATE);
Display Results After Join Operation
SELECT r.Reservation_ID, c.Customer_Name, h.Hall_Name, r.Reservation_Date
FROM Reservation r
JOIN Customer c ON r.Customer_ID = c.Customer_ID
JOIN Wedding_Hall h ON r.Hall_ID = h.Hall_ID;

b) Write a procedure to avail reduction in booking of wedding hall.

CREATE OR REPLACE PROCEDURE Avail_Reduction_In_Booking (


p_Hall_ID IN INT,
p_Percentage IN DECIMAL
) IS
v_Original_Capacity INT;
v_New_Capacity INT;
BEGIN
-- Fetch the original capacity of the hall
SELECT Capacity INTO v_Original_Capacity
FROM Wedding_Hall
WHERE Hall_ID = p_Hall_ID;

-- Calculate the new capacity after reduction


v_New_Capacity := v_Original_Capacity - (v_Original_Capacity * p_Percentage / 100);

-- Update the hall's capacity


UPDATE Wedding_Hall
SET Capacity = v_New_Capacity
WHERE Hall_ID = p_Hall_ID;

COMMIT;
DBMS_OUTPUT.PUT_LINE('Capacity reduced by ' || p_Percentage || '% for Hall ID ' ||
p_Hall_ID);
END;
/

28. Create a database for a car manufacturing company and use the having clause to
display the car models based on price.

Create Tables for Car Manufacturing Company


CREATE TABLE Car (
Car_ID INT PRIMARY KEY,
Car_Model VARCHAR(50),
Price DECIMAL(10, 2)
);

CREATE TABLE Manufacturer (


Manufacturer_ID INT PRIMARY KEY,
Manufacturer_Name VARCHAR(50)
);

CREATE TABLE Car_Manufacturing (


Car_ID INT,
Manufacturer_ID INT,
FOREIGN KEY (Car_ID) REFERENCES Car(Car_ID),
FOREIGN KEY (Manufacturer_ID) REFERENCES Manufacturer(Manufacturer_ID)
);

Insert Sample Data


INSERT INTO Car VALUES (1, 'Sedan', 20000);
INSERT INTO Car VALUES (2, 'SUV', 35000);
INSERT INTO Car VALUES (3, 'Hatchback', 15000);

INSERT INTO Manufacturer VALUES (1, 'Toyota');


INSERT INTO Manufacturer VALUES (2, 'Honda');

INSERT INTO Car_Manufacturing VALUES (1, 1);


INSERT INTO Car_Manufacturing VALUES (2, 2);
INSERT INTO Car_Manufacturing VALUES (3, 1);

Using HAVING Clause to Display Cars Based on Price

SELECT Car_Model, Price


FROM Car
GROUP BY Car_Model, Price
HAVING Price > 25000; -- Cars with price greater than 25,000

b) Write a procedure to insert and update the records in the above database.

Procedure to Insert Car Record

CREATE OR REPLACE PROCEDURE Insert_Car (


p_Car_Model IN VARCHAR,
p_Price IN DECIMAL
) IS
BEGIN
INSERT INTO Car (Car_Model, Price)
VALUES (p_Car_Model, p_Price);

COMMIT;
DBMS_OUTPUT.PUT_LINE('Car record inserted.');
END;
/

Procedure to Update Car Price

CREATE OR REPLACE PROCEDURE Update_Car_Price (


p_Car_ID IN INT,
p_New_Price IN DECIMAL
) IS
BEGIN
UPDATE Car
SET Price = p_New_Price
WHERE Car_ID = p_Car_ID;

COMMIT;
DBMS_OUTPUT.PUT_LINE('Car price updated.');
END;
/

29. Create and insert records in the student and course tables, and then use various join
operations to display the records.

PROGRAM:

Create Tables for Student and Course

CREATE TABLE Course (


cid NUMBER PRIMARY KEY,
cname VARCHAR2(20)
);
CREATE TABLE Student (
id NUMBER PRIMARY KEY,
name VARCHAR2(20),
cid NUMBER REFERENCES Course(cid)
);
Insert Sample Data

INSERT INTO Course VALUES (1, 'Math');


INSERT INTO Course VALUES (2, 'Sci');
INSERT INTO Course VALUES (3, 'Eng');

INSERT INTO Student VALUES (1, 'Anu', 1);


INSERT INTO Student VALUES (2, 'Bala', 2);
INSERT INTO Student VALUES (3, 'Cat', 3);
INSERT INTO Student VALUES (4, 'Dan', 1);

Display Records Using Join


-- INNER JOIN
SELECT s.name, c.cname FROM Student s JOIN Course c ON s.cid = c.cid;
-- LEFT OUTER JOIN
SELECT s.name, c.cname FROM Student s LEFT JOIN Course c ON s.cid = c.cid;
-- RIGHT OUTER JOIN
SELECT s.name, c.cname FROM Student s RIGHT JOIN Course c ON s.cid = c.cid;
-- FULL OUTER JOIN
SELECT s.name, c.cname FROM Student s FULL JOIN Course c ON s.cid = c.cid;

OUTPUT:
SELECT * FROM Student;

SELECT * FROM Course;

VARIOUS JOINS:
INNER JOIN:
LEFT OUTER JOIN:

RIGHT OUTER JOIN:

FULL OUTER JOIN:

b) Write a procedure to display day name while passing the day as number parameter.
(Example: if pass parameter as 1 it should display as Sunday.)

TEXT FILE:plsql29.sql(notepad)
CREATE OR REPLACE PROCEDURE Get_Day_Name(day_num IN NUMBER) AS
BEGIN
CASE day_num
WHEN 1 THEN DBMS_OUTPUT.PUT_LINE('Sunday');
WHEN 2 THEN DBMS_OUTPUT.PUT_LINE('Monday');
WHEN 3 THEN DBMS_OUTPUT.PUT_LINE('Tuesday');
WHEN 4 THEN DBMS_OUTPUT.PUT_LINE('Wednesday');
WHEN 5 THEN DBMS_OUTPUT.PUT_LINE('Thursday');
WHEN 6 THEN DBMS_OUTPUT.PUT_LINE('Friday');
WHEN 7 THEN DBMS_OUTPUT.PUT_LINE('Saturday');
ELSE DBMS_OUTPUT.PUT_LINE('Invalid day number');
END CASE;
END;
/
TO RUN:
SET SERVEROUTPUT ON;
@"C:\Users\Lenovo\Documents\DBMS\plsql29.sql";
EXEC Get_Day_Name(1);
OUTPUT:
Sunday
--------------
EXEC Get_Day_Name(3);
OUTPUT:
Tuesday

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy