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

Untitled 1

Uploaded by

madhanlap0402
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Untitled 1

Uploaded by

madhanlap0402
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

1.Create a Table as workers and the details are { S.

No, Name, Designation,


Branch } Perform the following commands:

i. Alter the table by adding a column Salary

ii. Alter the table by modifying the column Name

iii. Describe the table employee

iv. Copy the table employee as emp v. Truncate the table

vi. Delete the Second row from the table

vii. Drop the table.

viii. Write a PL/SQL program to print the given number is odd or even.

Step 1: Create the workers table


CREATE TABLE workers (
S_No INT,
Name VARCHAR(50),
Designation VARCHAR(50),
Branch VARCHAR(50)
);

Sample Output
S_No Name Designation Branch

i. Alter the table by adding a column Salary

ALTER TABLE workers


ADD Salary DECIMAL(10, 2);

Resulting Table Structure


S_No Name Designation Branch Salary

ii. Alter the table by modifying the column Name (Example: Increase the length)

ALTER TABLE workers


MODIFY Name VARCHAR(100);

iii. Describe the table workers

DESCRIBE workers;
Sample Output
Field Type Null Key Default Extra
S_No INT YES NULL
Name VARCHAR(100) YES NULL
Designation VARCHAR(50) YES NULL
Branch VARCHAR(50) YES NULL
Salary DECIMAL(10,2) YES NULL

iv. Copy the table workers as emp


CREATE TABLE emp AS
SELECT * FROM workers;

v. Truncate the table workers


TRUNCATE TABLE workers;

Sample Output
The table workers is now empty.

vi. Delete the second row from the table


To delete a specific row, we’ll add some sample data first and then delete based on conditions.

INSERT INTO workers (S_No, Name, Designation, Branch, Salary)


VALUES (1, 'John Doe', 'Manager', 'New York', 60000),
(2, 'Jane Smith', 'Analyst', 'Chicago', 50000),
(3, 'Sam Brown', 'Developer', 'San Francisco', 55000);

DELETE FROM workers WHERE S_No = 2;

Sample Output
S_No Name Designation Branch Salary
1 John Doe Manager New York 60000
3 Sam Brown Developer San Francisco 55000

vii. Drop the table workers

DROP TABLE workers;

Sample Output
The table workers is now deleted from the database.

viii. Write a PL/SQL program to print whether a given number is odd or even
Here’s a simple PL/SQL program to check if a number is odd or even:

DECLARE
num NUMBER := &Enter_Number;
BEGIN
IF MOD(num, 2) = 0 THEN
DBMS_OUTPUT.PUT_LINE(num || ' is Even');
ELSE
DBMS_OUTPUT.PUT_LINE(num || ' is Odd');
END IF;
END;
/

Sample Output
For example, if num is entered as 7, the output will be:
csharp
Copy code
7 is Odd

If num is 8, the output will be:


csharp
Copy code
8 is Even
2.Create the following tables student_details{register_no,
student_name, DOB, address, city} mark_details{register_no, mark1,
mark2, mark3, total }
i. Display only those rows whose total ranges between 250 and 300.
ii. Drop the table mark_details and Delete the row whose
register_no=161.
iii. Display all details whose names begins with 'a'.
iv. Write a PL/SQL program to print the details of the student
when regno is given as input

Step 1: Create student_details and mark_details tables

CREATE TABLE student_details (


register_no INT PRIMARY KEY,
student_name VARCHAR(50),
DOB DATE,
address VARCHAR(100),
city VARCHAR(50)
);

CREATE TABLE mark_details (


register_no INT,
mark1 INT,
mark2 INT,
mark3 INT,
total INT,
FOREIGN KEY (register_no) REFERENCES student_details(register_no)
);

Sample Data
Let's insert some sample data into both tables for demonstration purposes.

INSERT INTO student_details (register_no, student_name, DOB, address, city)


VALUES (161, 'Alice', TO_DATE('2002-03-15', 'YYYY-MM-DD'), '123 Maple St', 'New
York'),
(162, 'Alex', TO_DATE('2002-07-21', 'YYYY-MM-DD'), '456 Oak St', 'Los
Angeles'),
(163, 'Bob', TO_DATE('2001-10-10', 'YYYY-MM-DD'), '789 Pine St',
'Chicago'),
(164, 'Anna', TO_DATE('2002-05-05', 'YYYY-MM-DD'), '321 Elm St',
'Seattle');

INSERT INTO mark_details (register_no, mark1, mark2, mark3, total)


VALUES (161, 85, 90, 80, 255),
(162, 78, 88, 95, 261),
(163, 70, 60, 80, 210),
(164, 90, 85, 80, 255);
i. Display only those rows whose total ranges between 250 and 300

SELECT * FROM mark_details


WHERE total BETWEEN 250 AND 300;

Sample Output
register_no mark1 mark2 mark3 total
161 85 90 80 255
162 78 88 95 261
164 90 85 80 255

ii. Drop the table mark_details and delete the row whose register_no =
161
1. Drop the mark_details table:

DROP TABLE mark_details;

2. Delete the row in student_details with register_no = 161:

DELETE FROM student_details


WHERE register_no = 161;

Sample Output after Deletion


register_no student_name DOB address city
162 Alex 2002-07-21 456 Oak St Los Angeles
163 Bob 2001-10-10 789 Pine St Chicago
164 Anna 2002-05-05 321 Elm St Seattle

iii. Display all details whose names begin with 'A'

SELECT * FROM student_details


WHERE student_name LIKE 'A%';

Sample Output
register_no student_name DOB address city
162 Alex 2002-07-21 456 Oak St Los Angeles
164 Anna 2002-05-05 321 Elm St Seattle

iv. Write a PL/SQL program to print the details of the student when
register_no is given as input
Here’s a PL/SQL program that accepts a registration number as input and prints the student's details.

DECLARE
v_register_no student_details.register_no%TYPE := &Enter_RegNo;
v_student_name student_details.student_name%TYPE;
v_DOB student_details.DOB%TYPE;
v_address student_details.address%TYPE;
v_city student_details.city%TYPE;
BEGIN
SELECT student_name, DOB, address, city
INTO v_student_name, v_DOB, v_address, v_city
FROM student_details
WHERE register_no = v_register_no;

DBMS_OUTPUT.PUT_LINE('Student Details:');
DBMS_OUTPUT.PUT_LINE('Register No : ' || v_register_no);
DBMS_OUTPUT.PUT_LINE('Name : ' || v_student_name);
DBMS_OUTPUT.PUT_LINE('DOB : ' || TO_CHAR(v_DOB, 'YYYY-MM-DD'));
DBMS_OUTPUT.PUT_LINE('Address : ' || v_address);
DBMS_OUTPUT.PUT_LINE('City : ' || v_city);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No student found with Register No: ' ||
v_register_no);
END;
/

Sample Output
If the register_no is entered as 162, the output would be:

Student Details:
Register No : 162
Name : Alex
DOB : 2002-07-21
Address : 456 Oak St
City : Los Angeles

If no record is found, the output would be:


csharp
Copy code
No student found with Register No: [entered register_no]
3.Consider the following relational schema for a Loan database
application: Customer{Customer_id, Customer_name, Age, phone_no}
Loan{ Loan_id, Amount, Customer_id)}
i. Include the constraint on Loan_id that it starts with letter
‘L’.
ii. Display the list of the customer_ids and total Loan amount
taken.
iii. Display the Customer_id and Customer_name who have taken less
than two loans Write a PL/SQL program to print the details of the
customer when customerid is given as input

Step 1: Create Customer and Loan tables

CREATE TABLE Customer (


Customer_id INT PRIMARY KEY,
Customer_name VARCHAR(50),
Age INT,
phone_no VARCHAR(15)
);

CREATE TABLE Loan (


Loan_id VARCHAR(10) PRIMARY KEY,
Amount DECIMAL(10, 2),
Customer_id INT,
FOREIGN KEY (Customer_id) REFERENCES Customer(Customer_id)
);

i. Include the constraint on Loan_id that it starts with


letter ‘L’
To ensure that the Loan_id starts with the letter "L," we can add a check constraint.
ALTER TABLE Loan
ADD CONSTRAINT chk_Loan_id CHECK (Loan_id LIKE 'L%');

Sample Data
Let's add some sample data to the tables to demonstrate the queries.
INSERT INTO Customer (Customer_id, Customer_name, Age, phone_no)
VALUES (101, 'Alice', 30, '123-456-7890'),
(102, 'Bob', 45, '234-567-8901'),
(103, 'Carol', 28, '345-678-9012');

INSERT INTO Loan (Loan_id, Amount, Customer_id)


VALUES ('L001', 5000, 101),
('L002', 3000, 101),
('L003', 4000, 102),
('L004', 2500, 103);

ii. Display the list of Customer_id and total Loan amount


taken
SELECT Customer_id, SUM(Amount) AS Total_Loan_Amount
FROM Loan
GROUP BY Customer_id;

Sample Output
Customer_id Total_Loan_Amount
101 8000
102 4000
103 2500

iii. Display the Customer_id and Customer_name of


customers who have taken less than two loans
To get the list of customers who have taken less than two loans, we can use a HAVING clause.
SELECT c.Customer_id, c.Customer_name
FROM Customer c
JOIN Loan l ON c.Customer_id = l.Customer_id
GROUP BY c.Customer_id, c.Customer_name
HAVING COUNT(l.Loan_id) < 2;

Sample Output
Customer_id Customer_name
102 Bob
103 Carol

iv. Write a PL/SQL program to print the details of the


customer when Customer_id is given as input
Here’s a PL/SQL program that takes a Customer_id as input and prints the customer's details.
DECLARE
v_Customer_id Customer.Customer_id%TYPE := &Enter_CustomerID;
v_Customer_name Customer.Customer_name%TYPE;
v_Age Customer.Age%TYPE;
v_phone_no Customer.phone_no%TYPE;
BEGIN
SELECT Customer_name, Age, phone_no
INTO v_Customer_name, v_Age, v_phone_no
FROM Customer
WHERE Customer_id = v_Customer_id;

DBMS_OUTPUT.PUT_LINE('Customer Details:');
DBMS_OUTPUT.PUT_LINE('Customer ID : ' || v_Customer_id);
DBMS_OUTPUT.PUT_LINE('Name : ' || v_Customer_name);
DBMS_OUTPUT.PUT_LINE('Age : ' || v_Age);
DBMS_OUTPUT.PUT_LINE('Phone Number : ' || v_phone_no);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No customer found with Customer ID:
' || v_Customer_id);
END;
/

Sample Output
If the Customer_id is entered as 101, the output would be:

Customer Details:
Customer ID : 101
Name : Alice
Age : 30
Phone Number : 123-456-7890
If no record is found, the output will be:
No customer found with Customer ID: [entered Customer_id]
4.Consider the following database for a Banking Enterprise.
Branch{branch_name, branch_city, assets) Account(accno,
branch_name, balance} Depositor {customer_name, accno)
Customer(customer_name, customer_street, customer_city} Loan
{loan_number, branch_name, amount} Borrower { customer_name,
loan_number)}
i. Create the above tables by properly specifying the primary keys
and foreign keys and enter at least five tuples for each relation.
ii. Find all the customers who have at least two accounts at the
main branch.
iii. Find all the customers who have an account at all the
branches located in a specific city. iv. Write a PL/SQL program to
delete all account tuples at every branch located in a specific
city

Step 1: Create the Tables with Primary and Foreign Key Constraints
CREATE TABLE Branch (
branch_name VARCHAR(50) PRIMARY KEY,
branch_city VARCHAR(50),
assets DECIMAL(15, 2)
);

CREATE TABLE Account (


accno INT PRIMARY KEY,
branch_name VARCHAR(50),
balance DECIMAL(10, 2),
FOREIGN KEY (branch_name) REFERENCES Branch(branch_name)
);

CREATE TABLE Depositor (


customer_name VARCHAR(50),
accno INT,
PRIMARY KEY (customer_name, accno),
FOREIGN KEY (accno) REFERENCES Account(accno)
);

CREATE TABLE Customer (


customer_name VARCHAR(50) PRIMARY KEY,
customer_street VARCHAR(100),
customer_city VARCHAR(50)
);

CREATE TABLE Loan (


loan_number INT PRIMARY KEY,
branch_name VARCHAR(50),
amount DECIMAL(10, 2),
FOREIGN KEY (branch_name) REFERENCES Branch(branch_name)
);

CREATE TABLE Borrower (


customer_name VARCHAR(50),
loan_number INT,
PRIMARY KEY (customer_name, loan_number),
FOREIGN KEY (customer_name) REFERENCES
Customer(customer_name),
FOREIGN KEY (loan_number) REFERENCES Loan(loan_number)
);

Sample Data Insertion


Let’s insert sample data for each table. This is just sample data for demonstration.

-- Inserting data into Branch


INSERT INTO Branch (branch_name, branch_city, assets) VALUES
('Main', 'New York', 1000000),
('North', 'New York', 500000),
('South', 'Los Angeles', 750000),
('East', 'Chicago', 650000),
('West', 'San Francisco', 800000);

-- Inserting data into Account


INSERT INTO Account (accno, branch_name, balance) VALUES
(1001, 'Main', 2000),
(1002, 'Main', 3000),
(1003, 'North', 1500),
(1004, 'South', 2500),
(1005, 'East', 1200);

-- Inserting data into Depositor


INSERT INTO Depositor (customer_name, accno) VALUES
('Alice', 1001),
('Alice', 1002),
('Bob', 1003),
('Carol', 1004),
('David', 1005);

-- Inserting data into Customer


INSERT INTO Customer (customer_name, customer_street,
customer_city) VALUES
('Alice', '123 Maple St', 'New York'),
('Bob', '456 Oak St', 'New York'),
('Carol', '789 Pine St', 'Los Angeles'),
('David', '321 Elm St', 'Chicago'),
('Eve', '654 Birch St', 'San Francisco');

-- Inserting data into Loan


INSERT INTO Loan (loan_number, branch_name, amount) VALUES
(2001, 'Main', 5000),
(2002, 'North', 3000),
(2003, 'South', 4000),
(2004, 'East', 6000),
(2005, 'West', 7000);

-- Inserting data into Borrower


INSERT INTO Borrower (customer_name, loan_number) VALUES

ii. Find all the customers who have at least two accounts
at the Main branch

SELECT d.customer_name
FROM Depositor d
JOIN Account a ON d.accno = a.accno
WHERE a.branch_name = 'Main'
GROUP BY d.customer_name
HAVING COUNT(d.accno) >= 2;

Sample Output
customer_name
Alice

iii. Find all the customers who have an account at all the branches located in a
specific city (e.g., 'New York')
To find customers who have an account at all branches in a specific city, say New York, we’ll use
a subquery.

SELECT d.customer_name
FROM Depositor d
JOIN Account a ON d.accno = a.accno
JOIN Branch b ON a.branch_name = b.branch_name
WHERE b.branch_city = 'New York'
GROUP BY d.customer_name
HAVING COUNT(DISTINCT a.branch_name) = (SELECT COUNT(branch_name)
FROM Branch
WHERE branch_city = 'New York');

Sample Output
customer_name
Alice
Bob

iv. Write a PL/SQL program to delete all account tuples at every branch located
in a specific city
Here's a PL/SQL program that deletes all account records for branches located in a specified city.
The program will take the city as input.
DECLARE
v_city VARCHAR(50) := '&Enter_City';
BEGIN
DELETE FROM Account
WHERE branch_name IN (SELECT branch_name FROM Branch WHERE branch_city =
v_city);

DBMS_OUTPUT.PUT_LINE('All accounts in branches located in ' || v_city || '


have been deleted.');
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
/

Sample Output
If the input city is New York, the output will be:

All accounts in branches located in New York have been deleted.


5.Consider the following database consisting of the following
tables:
Hostel (hno, hname, type [boys/girls])
Menu (hno, day, breakfast, lunch, dinner)
Warden (wname, qual, hno)
Student (sid, sname, gender, year, hno)
i. Display the total number of girls and boys hostel in the
college.
ii. Display the menu in the hostel ‘x’ on Tuesday.
iii. Display the number of wardens for each hostel.II.
iv. Write a PL/SQL program to print given number is Prime or not

Step 1: Create the Tables


sql
Copy code
CREATE TABLE Hostel (
hno INT PRIMARY KEY,
hname VARCHAR(50),
type VARCHAR(5) CHECK (type IN ('boys', 'girls'))
);

CREATE TABLE Menu (


hno INT,
day VARCHAR(10),
breakfast VARCHAR(50),
lunch VARCHAR(50),
dinner VARCHAR(50),
PRIMARY KEY (hno, day),
FOREIGN KEY (hno) REFERENCES Hostel(hno)
);

CREATE TABLE Warden (


wname VARCHAR(50),
qual VARCHAR(50),
hno INT,
FOREIGN KEY (hno) REFERENCES Hostel(hno)
);

CREATE TABLE Student (


sid INT PRIMARY KEY,
sname VARCHAR(50),
gender VARCHAR(10),
year INT,
hno INT,
FOREIGN KEY (hno) REFERENCES Hostel(hno)
);
Sample Data Insertion
Let's add some sample data for demonstration.
sql
Copy code
-- Inserting data into Hostel
INSERT INTO Hostel (hno, hname, type) VALUES
(1, 'Alpha Hostel', 'boys'),
(2, 'Beta Hostel', 'girls'),
(3, 'Gamma Hostel', 'boys'),
(4, 'Delta Hostel', 'girls');

-- Inserting data into Menu


INSERT INTO Menu (hno, day, breakfast, lunch, dinner) VALUES
(1, 'Monday', 'Pancakes', 'Pizza', 'Pasta'),
(2, 'Tuesday', 'Toast', 'Burger', 'Spaghetti'),
(3, 'Wednesday', 'Cereal', 'Rice', 'Salad'),
(4, 'Tuesday', 'Eggs', 'Chicken', 'Soup');

-- Inserting data into Warden


INSERT INTO Warden (wname, qual, hno) VALUES
('John Doe', 'MBA', 1),
('Jane Smith', 'B.Ed', 2),
('Paul White', 'M.Ed', 3),
('Emily Brown', 'PhD', 4);

-- Inserting data into Student


INSERT INTO Student (sid, sname, gender, year, hno) VALUES
(101, 'Alice', 'female', 1, 2),
(102, 'Bob', 'male', 2, 1),
(103, 'Carol', 'female', 3, 4),
(104, 'David', 'male', 1, 3),
(105, 'Eva', 'female', 2, 2);

i. Display the total number of boys' and girls' hostels in the college
sql
Copy code
SELECT type, COUNT(*) AS Total_Hostels
FROM Hostel
GROUP BY type;

Sample Output
type Total_Hostels
boys 2
girls 2

ii. Display the menu in the hostel ‘x’ on Tuesday


Assuming x is Beta Hostel, which corresponds to hno = 2.
sql
Copy code
SELECT breakfast, lunch, dinner
FROM Menu
WHERE hno = (SELECT hno FROM Hostel WHERE hname = 'Beta Hostel')
AND day = 'Tuesday';
Sample Output
breakfast lunch dinner
Toast Burger Spaghetti

iii. Display the number of wardens for each hostel


sql
Copy code
SELECT h.hname, COUNT(w.wname) AS Number_of_Wardens
FROM Hostel h
LEFT JOIN Warden w ON h.hno = w.hno
GROUP BY h.hname;

Sample Output
hname Number_of_Wardens
Alpha Hostel 1
Beta Hostel 1
Gamma Hostel 1
Delta Hostel 1

iv. Write a PL/SQL program to check if a given number is prime


Here's a PL/SQL program that accepts a number as input and checks if it is prime.
sql
Copy code
DECLARE
num INT := &Enter_Number;
is_prime BOOLEAN := TRUE;
i INT := 2;
BEGIN
IF num <= 1 THEN
is_prime := FALSE;
ELSE
WHILE i <= SQRT(num) LOOP
IF num MOD i = 0 THEN
is_prime := FALSE;
EXIT;
END IF;
i := i + 1;
END LOOP;
END IF;

IF is_prime THEN
DBMS_OUTPUT.PUT_LINE(num || ' is a prime number.');
ELSE
DBMS_OUTPUT.PUT_LINE(num || ' is not a prime number.');
END IF;
END;
/

Sample Output
If the entered number is 7:
csharp
Copy code
7 is a prime number.
If the entered number is 10:
csharp
Copy code
10 is not a prime number.

8.Consider the employee relational database, Where the primary


keys are underlined. Employee ( employee_name, street, city) Works
( employee_name, company_name, salary) Company ( comapny_name,
city) Manages ( employee_name, manager_name)
a) Find all employees in the database who earn more than each
employee of Small Bank Corporation.
b) Assume that the companies may be located in several cities.
Find all companies located in every city in which Small Bank
Corporation is located.
c) Give all managers of first Bank Corporation a 10 percent raise
unless the salary becomes greater than $100,000; in such cases,
give only a 3 percent raise.
d) Write a PL/SQL program to print given number Armstrong or not.

Step 1: Create the Tables


sql
Copy code
CREATE TABLE Employee (
employee_name VARCHAR(50) PRIMARY KEY,
street VARCHAR(100),
city VARCHAR(50)
);

CREATE TABLE Works (


employee_name VARCHAR(50),
company_name VARCHAR(50),
salary DECIMAL(10, 2),
PRIMARY KEY (employee_name, company_name),
FOREIGN KEY (employee_name) REFERENCES Employee(employee_name)
);

CREATE TABLE Company (


company_name VARCHAR(50) PRIMARY KEY,
city VARCHAR(50)
);

CREATE TABLE Manages (


employee_name VARCHAR(50),
manager_name VARCHAR(50),
PRIMARY KEY (employee_name, manager_name),
FOREIGN KEY (employee_name) REFERENCES Employee(employee_name),
FOREIGN KEY (manager_name) REFERENCES Employee(employee_name)
);

Sample Data Insertion


Let's add some sample data for demonstration.
sql
Copy code
-- Inserting data into Employee
INSERT INTO Employee (employee_name, street, city) VALUES
('Alice', '123 Maple St', 'New York'),
('Bob', '456 Oak St', 'Los Angeles'),
('Carol', '789 Pine St', 'New York'),
('David', '321 Elm St', 'Chicago'),
('Eve', '654 Birch St', 'San Francisco');

-- Inserting data into Works


INSERT INTO Works (employee_name, company_name, salary) VALUES
('Alice', 'Small Bank Corporation', 60000),
('Bob', 'First Bank Corporation', 95000),
('Carol', 'First Bank Corporation', 85000),
('David', 'Small Bank Corporation', 70000),
('Eve', 'Big Bank Corporation', 120000);

-- Inserting data into Company


INSERT INTO Company (company_name, city) VALUES
('Small Bank Corporation', 'New York'),
('Small Bank Corporation', 'Chicago'),
('First Bank Corporation', 'New York'),
('Big Bank Corporation', 'San Francisco');

-- Inserting data into Manages


INSERT INTO Manages (employee_name, manager_name) VALUES
('Bob', 'Alice'),
('Carol', 'Alice'),
('David', 'Eve'),
('Eve', 'Bob');

a) Find all employees in the database who earn more than each employee of
Small Bank Corporation
To find employees who earn more than each employee of Small Bank Corporation, we’ll
use a subquery.
sql
Copy code
SELECT w1.employee_name
FROM Works w1
WHERE w1.salary > ALL (
SELECT w2.salary
FROM Works w2
WHERE w2.company_name = 'Small Bank Corporation'
);

Sample Output
employee_name
Eve

b) Find all companies located in every city in which Small Bank


Corporation is located
sql
Copy code
SELECT DISTINCT c.company_name
FROM Company c
WHERE NOT EXISTS (
SELECT city
FROM Company
WHERE company_name = 'Small Bank Corporation'
AND city NOT IN (
SELECT city
FROM Company
WHERE company_name = c.company_name
)
);

Sample Output
company_name
Small Bank Corporation
First Bank Corporation

c) Give all managers of First Bank Corporation a 10 percent raise unless


the salary becomes greater than $100,000; in such cases, give only a 3 percent
raise
We’ll identify managers working for First Bank Corporation and apply the raise
conditionally.
sql
Copy code
UPDATE Works
SET salary = CASE
WHEN salary * 1.10 <= 100000 THEN salary * 1.10
ELSE salary * 1.03
END
WHERE employee_name IN (
SELECT m.manager_name
FROM Manages m
JOIN Works w ON m.manager_name = w.employee_name
WHERE w.company_name = 'First Bank Corporation'
);

Sample Output
employee_name company_name salary
Bob First Bank Corporation 103500

d) Write a PL/SQL program to check if a given number is an Armstrong number


Here's a PL/SQL program that takes a number as input and checks if it is an Armstrong number.
sql
Copy code
DECLARE
num INT := &Enter_Number;
original_num INT := num;
result INT := 0;
digit INT;
BEGIN
WHILE num > 0 LOOP
digit := num MOD 10;
result := result + POWER(digit, 3);
num := num / 10;
END LOOP;
IF result = original_num THEN
DBMS_OUTPUT.PUT_LINE(original_num || ' is an Armstrong number.');
ELSE
DBMS_OUTPUT.PUT_LINE(original_num || ' is not an Armstrong number.');
END IF;
END;
/

Sample Output
If the entered number is 153:
csharp
Copy code
153 is an Armstrong number.

If the entered number is 123:


csharp
Copy code
123 is not an Armstrong number.
9.Consider the following relational schema: Employee( empno, name,
office, age ) Books ( isbn, title, authors, publisher )
Loan( empno, isbn, date ) Write the following queries in SQL:
a) Print the names of employees who have borrowed any books
published by McGrawHill.
b) Print the names of employees who have borrowed all books
published by McGrawHill.
c) For each publishers, print the names of employees who have
borrowed more than five books of that publisher.
d) Write a PL/SQL program to print the greatest of three numbers

Step 1: Create the Tables


sql
Copy code
CREATE TABLE Employee (
empno INT PRIMARY KEY,
name VARCHAR(50),
office VARCHAR(50),
age INT
);

CREATE TABLE Books (


isbn VARCHAR(20) PRIMARY KEY,
title VARCHAR(100),
authors VARCHAR(100),
publisher VARCHAR(50)
);

CREATE TABLE Loan (


empno INT,
isbn VARCHAR(20),
date DATE,
PRIMARY KEY (empno, isbn),
FOREIGN KEY (empno) REFERENCES Employee(empno),
FOREIGN KEY (isbn) REFERENCES Books(isbn)
);

Sample Data Insertion


Let's add some sample data for demonstration.
sql
Copy code
-- Inserting data into Employee
INSERT INTO Employee (empno, name, office, age) VALUES
(1, 'Alice', 'New York', 30),
(2, 'Bob', 'Los Angeles', 45),
(3, 'Carol', 'Chicago', 28),
(4, 'David', 'San Francisco', 40),
(5, 'Eve', 'New York', 35);

-- Inserting data into Books


INSERT INTO Books (isbn, title, authors, publisher) VALUES
('1111', 'SQL Basics', 'John Doe', 'McGrawHill'),
('2222', 'Advanced SQL', 'Jane Smith', 'McGrawHill'),
('3333', 'Database Design', 'Alice Brown', 'Pearson'),
('4444', 'Data Structures', 'Eve White', 'McGrawHill'),
('5555', 'Computer Networks', 'Paul Black', 'Pearson');

-- Inserting data into Loan


INSERT INTO Loan (empno, isbn, date) VALUES
(1, '1111', '2024-10-01'),
(2, '1111', '2024-09-20'),
(3, '2222', '2024-09-25'),
(1, '4444', '2024-09-15'),
(2, '2222', '2024-08-10'),
(4, '3333', '2024-07-01'),
(5, '1111', '2024-06-01'),
(5, '2222', '2024-06-05'),
(5, '4444', '2024-06-10'),
(3, '1111', '2024-05-01');

a) Print the names of employees who have borrowed any books published by
McGrawHill
sql
Copy code
SELECT DISTINCT e.name
FROM Employee e
JOIN Loan l ON e.empno = l.empno
JOIN Books b ON l.isbn = b.isbn
WHERE b.publisher = 'McGrawHill';

Sample Output
name
Alice
Bob
Carol
Eve

b) Print the names of employees who have borrowed all books published by
McGrawHill
To check if an employee has borrowed all books published by McGrawHill, we need to compare the
count of distinct McGrawHill books borrowed by each employee with the total number of
McGrawHill books.
sql
Copy code
SELECT e.name
FROM Employee e
JOIN Loan l ON e.empno = l.empno
JOIN Books b ON l.isbn = b.isbn
WHERE b.publisher = 'McGrawHill'
GROUP BY e.name
HAVING COUNT(DISTINCT b.isbn) = (SELECT COUNT(DISTINCT isbn) FROM Books WHERE
publisher = 'McGrawHill');
Sample Output
name
Eve

c) For each publisher, print the names of employees who have borrowed more
than five books of that publisher
sql
Copy code
SELECT b.publisher, e.name
FROM Employee e
JOIN Loan l ON e.empno = l.empno
JOIN Books b ON l.isbn = b.isbn
GROUP BY b.publisher, e.name
HAVING COUNT(l.isbn) > 5;

Sample Output
(Adjust the table as necessary based on actual data.)

publisher name
Pearson Eve

d) Write a PL/SQL program to print the greatest of three numbers


Here's a PL/SQL program that takes three numbers as input and prints the greatest of the three.
sql
Copy code
DECLARE
num1 INT := &Enter_Number1;
num2 INT := &Enter_Number2;
num3 INT := &Enter_Number3;
greatest INT;
BEGIN
IF num1 >= num2 AND num1 >= num3 THEN
greatest := num1;
ELSIF num2 >= num1 AND num2 >= num3 THEN
greatest := num2;
ELSE
greatest := num3;
END IF;

DBMS_OUTPUT.PUT_LINE('The greatest number is: ' || greatest);


END;
/

Sample Output
If the input numbers are 45, 78, and 32:
csharp
Copy code
The greatest number is: 78
10.i. Create a table as book (sl.no, book_name, author_name,price,
edition,publisher_name ). Perform the following operations:
a) Insert minimum ten tuples in book table
b) Commit the table book
c) Create a save point for the table book as B
d) Rollback the table book after inserting 4 & 5 row e) Define
Grant & Revoke ii.Create a view contains slno,book_name,price. iv.
Write a PL/SQL program to print the greatest of two numbers

Step 1: Create the book Table


sql
Copy code
CREATE TABLE book (
sl_no INT PRIMARY KEY,
book_name VARCHAR(100),
author_name VARCHAR(100),
price DECIMAL(10, 2),
edition INT,
publisher_name VARCHAR(100)
);

a) Insert Minimum Ten Tuples in book Table


sql
Copy code
INSERT INTO book (sl_no, book_name, author_name, price, edition, publisher_name)
VALUES
(1, 'SQL Fundamentals', 'John Doe', 25.00, 1, 'Pearson'),
(2, 'Advanced SQL', 'Jane Smith', 30.00, 2, 'McGrawHill'),
(3, 'Database Management', 'Alice Brown', 45.00, 3, 'O\'Reilly'),
(4, 'Data Structures', 'Bob White', 50.00, 2, 'Wiley'),
(5, 'Introduction to Algorithms', 'Carol Green', 60.00, 1, 'MIT Press'),
(6, 'Python Programming', 'David Black', 35.00, 1, 'Packt'),
(7, 'Machine Learning', 'Eve Blue', 55.00, 1, 'Springer'),
(8, 'Data Science Handbook', 'Frank Red', 40.00, 1, 'Cambridge'),
(9, 'AI Basics', 'Grace Grey', 30.00, 1, 'O\'Reilly'),
(10, 'Big Data Analytics', 'Henry Yellow', 65.00, 2, 'McGrawHill');

b) Commit the book Table


sql
Copy code
COMMIT;

c) Create a Savepoint for the book Table as B


sql
Copy code
SAVEPOINT B;
d) Rollback the book Table after Inserting Rows 4 & 5
To roll back to the state after inserting rows 4 and 5, you would first insert the first three rows,
create the savepoint, insert rows 4 and 5, and then roll back to the savepoint.
Here's a sequence:
sql
Copy code
-- Insert the first three rows
INSERT INTO book (sl_no, book_name, author_name, price, edition, publisher_name)
VALUES
(1, 'SQL Fundamentals', 'John Doe', 25.00, 1, 'Pearson'),
(2, 'Advanced SQL', 'Jane Smith', 30.00, 2, 'McGrawHill'),
(3, 'Database Management', 'Alice Brown', 45.00, 3, 'O\'Reilly');

-- Commit and create a savepoint


COMMIT;
SAVEPOINT B;

-- Insert rows 4 and 5


INSERT INTO book (sl_no, book_name, author_name, price, edition, publisher_name)
VALUES
(4, 'Data Structures', 'Bob White', 50.00, 2, 'Wiley'),
(5, 'Introduction to Algorithms', 'Carol Green', 60.00, 1, 'MIT Press');

-- Rollback to savepoint B
ROLLBACK TO B;

After rolling back, only rows 1-3 will remain in the table.

e) Define GRANT and REVOKE


• GRANT: The GRANT command is used to provide users with access privileges to the
database. You can grant permissions like SELECT, INSERT, UPDATE, etc., on specific
tables or the entire database.
sql
Copy code
GRANT SELECT, INSERT ON book TO some_user;

• REVOKE: The REVOKE command is used to remove previously granted privileges from a
user or role.
sql
Copy code
REVOKE INSERT ON book FROM some_user;

ii. Create a View Containing sl_no, book_name, and price


sql
Copy code
CREATE VIEW book_view AS
SELECT sl_no, book_name, price
FROM book;

Sample Output of the View


To see the content of book_view:
sql
Copy code
SELECT * FROM book_view;

sl_no book_name price


1 SQL Fundamentals 25.00
2 Advanced SQL 30.00
3 Database Management 45.00
... ... ...

iv. Write a PL/SQL Program to Print the Greatest of Two Numbers


Here's a PL/SQL program that takes two numbers as input and prints the greatest of the two.

DECLARE
num1 INT := &Enter_Number1;
num2 INT := &Enter_Number2;
BEGIN
IF num1 > num2 THEN
DBMS_OUTPUT.PUT_LINE('The greatest number is: ' || num1);
ELSIF num2 > num1 THEN
DBMS_OUTPUT.PUT_LINE('The greatest number is: ' || num2);
ELSE
DBMS_OUTPUT.PUT_LINE('Both numbers are equal: ' || num1);
END IF;
END;
/

Sample Output
If the entered numbers are 45 and 78:

The greatest number is: 78

If the entered numbers are 50 and 50:

Both numbers are equal: 50


11.Create a table salesman{ salesman_id, name, city, commission }
and customer{customer_id, name, city, grade, slaesman_id}. Write
the following query:
a) Create a view for those salesmen belongs to the city New York
b) Create a view for all salesmen with columns salesman_id, name,
and city
c) Find the salesmen of the city New York who achieved the
commission more than 13%. d) Create a view to getting a count of
how many customers we have at each level of a grade
e) Write a PL/SQL program to print the greatest of three numbers

Step 1: Create the Tables


sql
Copy code
CREATE TABLE salesman (
salesman_id INT PRIMARY KEY,
name VARCHAR(100),
city VARCHAR(50),
commission DECIMAL(5, 2) -- percentage as a decimal (e.g., 0.13 for 13%)
);

CREATE TABLE customer (


customer_id INT PRIMARY KEY,
name VARCHAR(100),
city VARCHAR(50),
grade CHAR(1), -- Assuming grades are A, B, C, etc.
salesman_id INT,
FOREIGN KEY (salesman_id) REFERENCES salesman(salesman_id)
);

Sample Data Insertion


Let's add some sample data to the tables.
sql
Copy code
-- Inserting data into salesman
INSERT INTO salesman (salesman_id, name, city, commission) VALUES
(1, 'Alice Johnson', 'New York', 0.15),
(2, 'Bob Smith', 'Los Angeles', 0.10),
(3, 'Carol White', 'New York', 0.12),
(4, 'David Brown', 'Chicago', 0.20),
(5, 'Eve Black', 'New York', 0.14);

-- Inserting data into customer


INSERT INTO customer (customer_id, name, city, grade, salesman_id) VALUES
(1, 'Frank Green', 'New York', 'A', 1),
(2, 'Grace Blue', 'Los Angeles', 'B', 2),
(3, 'Henry Red', 'New York', 'C', 3),
(4, 'Ivy Yellow', 'Chicago', 'A', 4),
(5, 'Jack Orange', 'New York', 'B', 5),
(6, 'Kim Purple', 'Los Angeles', 'C', 2),
(7, 'Liam Grey', 'Chicago', 'A', 4);

a) Create a View for Salesmen Belonging to the City New York


sql
Copy code
CREATE VIEW new_york_salesmen AS
SELECT *
FROM salesman
WHERE city = 'New York';

b) Create a View for All Salesmen with Columns salesman_id, name, and
city
sql
Copy code
CREATE VIEW all_salesmen AS
SELECT salesman_id, name, city
FROM salesman;

c) Find the Salesmen of the City New York Who Achieved the Commission More
Than 13%
sql
Copy code
SELECT *
FROM salesman
WHERE city = 'New York' AND commission > 0.13;

Sample Output
salesman_id name city commission
1 Alice Johnson New York 0.15
5 Eve Black New York 0.14

d) Create a View to Get a Count of How Many Customers We Have at Each


Level of a Grade
sql
Copy code
CREATE VIEW grade_count AS
SELECT grade, COUNT(*) AS customer_count
FROM customer
GROUP BY grade;

Sample Output from the View


To see the content of grade_count:
sql
Copy code
SELECT * FROM grade_count;

grade customer_count
A 3
B 3
grade customer_count
C 2

e) Write a PL/SQL Program to Print the Greatest of Three Numbers


Here's a PL/SQL program that takes three numbers as input and prints the greatest of the three.
sql
Copy code
DECLARE
num1 INT := &Enter_Number1;
num2 INT := &Enter_Number2;
num3 INT := &Enter_Number3;
greatest INT;
BEGIN
IF num1 >= num2 AND num1 >= num3 THEN
greatest := num1;
ELSIF num2 >= num1 AND num2 >= num3 THEN
greatest := num2;
ELSE
greatest := num3;
END IF;

DBMS_OUTPUT.PUT_LINE('The greatest number is: ' || greatest);


END;
/

Sample Output
If the entered numbers are 45, 78, and 32:
csharp
Copy code
The greatest number is: 78

If the entered numbers are 50, 50, and 30:


csharp
Copy code
The greatest number is: 50
12.Consider the following relational schema for a Loan database
application: Customer{Customer_id, Customer_name, Age, phone_no}
Loan{ Loan_id, Amount, Customer_id)}
i. Include the constraint on Loan_id that it starts with letter
‘L’.
ii. Display the list of the customer_ids and total Loan amount
taken.
iii. Display the Customer_id and Customer_name who have taken less
than two loans iv.Write a PL/SQL program to print the details of
the customer when customerid is given as input.

Step 1: Create the Tables


sql
Copy code
CREATE TABLE Customer (
Customer_id INT PRIMARY KEY,
Customer_name VARCHAR(100),
Age INT,
phone_no VARCHAR(15)
);

CREATE TABLE Loan (


Loan_id VARCHAR(10) PRIMARY KEY CHECK (Loan_id LIKE 'L%'), -- Constraint
that Loan_id starts with 'L'
Amount DECIMAL(10, 2),
Customer_id INT,
FOREIGN KEY (Customer_id) REFERENCES Customer(Customer_id)
);

Sample Data Insertion


Let's add some sample data to the tables.
sql
Copy code
-- Inserting data into Customer
INSERT INTO Customer (Customer_id, Customer_name, Age, phone_no) VALUES
(1, 'Alice Johnson', 30, '555-1234'),
(2, 'Bob Smith', 45, '555-5678'),
(3, 'Carol White', 28, '555-8765'),
(4, 'David Brown', 40, '555-4321'),
(5, 'Eve Black', 35, '555-6789');

-- Inserting data into Loan


INSERT INTO Loan (Loan_id, Amount, Customer_id) VALUES
('L001', 1000.00, 1),
('L002', 2000.00, 1),
('L003', 1500.00, 2),
('L004', 500.00, 3),
('L005', 2500.00, 3),
('L006', 3000.00, 4);
ii. Display the List of the Customer_ids and Total Loan Amount Taken
sql
Copy code
SELECT Customer_id, SUM(Amount) AS Total_Loan_Amount
FROM Loan
GROUP BY Customer_id;

Sample Output
Customer_id Total_Loan_Amount
1 3000.00
2 1500.00
3 3000.00
4 3000.00

iii. Display the Customer_id and Customer_name Who Have Taken Less Than
Two Loans
sql
Copy code
SELECT c.Customer_id, c.Customer_name
FROM Customer c
LEFT JOIN Loan l ON c.Customer_id = l.Customer_id
GROUP BY c.Customer_id, c.Customer_name
HAVING COUNT(l.Loan_id) < 2;

Sample Output
Customer_id Customer_name
2 Bob Smith
4 David Brown

iv. Write a PL/SQL Program to Print the Details of the Customer When
customerid is Given as Input
Here’s a PL/SQL program that takes a customer ID as input and prints the customer's details.
sql
Copy code
DECLARE
v_customer_id INT := &Enter_CustomerID; -- Prompt for customer ID
v_customer_name VARCHAR(100);
v_age INT;
v_phone_no VARCHAR(15);
BEGIN
SELECT Customer_name, Age, phone_no
INTO v_customer_name, v_age, v_phone_no
FROM Customer
WHERE Customer_id = v_customer_id;

DBMS_OUTPUT.PUT_LINE('Customer ID: ' || v_customer_id);


DBMS_OUTPUT.PUT_LINE('Customer Name: ' || v_customer_name);
DBMS_OUTPUT.PUT_LINE('Age: ' || v_age);
DBMS_OUTPUT.PUT_LINE('Phone Number: ' || v_phone_no);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No customer found with ID: ' || v_customer_id);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
/

Sample Output
If the input customer ID is 1:
yaml
Copy code
Customer ID: 1
Customer Name: Alice Johnson
Age: 30
Phone Number: 555-1234

If the input customer ID is 6 (which does not exist):


csharp
Copy code
No customer found with ID: 6
13..Create the following tables with the mapping given below.
stu_details(reg_no, stu_name, DOB, address, city)
mark_details(reg_no, mark1, mark2, mark3, total)
(a) Alter the table mark_details to add a column average with data
type as long.
(b) Display the months between the DOB and till date.
(c) Using alter command drop the column address from the table
stu_details. (d) Write a PL/SQL program to find the sum & average
marks of all the student using procedures. Create the following
tables with the mapping given below.

Step 1: Create the Tables


sql
Copy code
CREATE TABLE stu_details (
reg_no INT PRIMARY KEY,
stu_name VARCHAR(100),
DOB DATE,
address VARCHAR(255),
city VARCHAR(100)
);

CREATE TABLE mark_details (


reg_no INT PRIMARY KEY,
mark1 INT,
mark2 INT,
mark3 INT,
total INT,
FOREIGN KEY (reg_no) REFERENCES stu_details(reg_no)
);

Sample Data Insertion


Let's add some sample data to the tables.
sql
Copy code
-- Inserting data into stu_details
INSERT INTO stu_details (reg_no, stu_name, DOB, address, city) VALUES
(101, 'Alice Johnson', TO_DATE('2000-01-15', 'YYYY-MM-DD'), '123 Main St', 'New
York'),
(102, 'Bob Smith', TO_DATE('1999-04-22', 'YYYY-MM-DD'), '456 Maple Ave', 'Los
Angeles'),
(103, 'Carol White', TO_DATE('2001-07-30', 'YYYY-MM-DD'), '789 Elm St',
'Chicago');

-- Inserting data into mark_details


INSERT INTO mark_details (reg_no, mark1, mark2, mark3, total) VALUES
(101, 85, 90, 78, 253),
(102, 88, 76, 91, 255),
(103, 90, 85, 82, 257);
a) Alter the Table mark_details to Add a Column average
sql
Copy code
ALTER TABLE mark_details
ADD average NUMBER; -- Assuming average will be a numeric type

b) Display the Months Between the DOB and Current Date


sql
Copy code
SELECT reg_no, stu_name,
MONTHS_BETWEEN(SYSDATE, DOB) AS months_since_dob
FROM stu_details;

Sample Output
reg_no stu_name months_since_dob
101 Alice Johnson 297
102 Bob Smith 303
103 Carol White 274

c) Using ALTER Command Drop the Column address from the Table
stu_details
sql
Copy code
ALTER TABLE stu_details
DROP COLUMN address;

d) Write a PL/SQL Program to Find the Sum & Average Marks of All Students
Using Procedures
Here’s a PL/SQL program that calculates the total and average marks of all students.
sql
Copy code
CREATE OR REPLACE PROCEDURE calculate_marks AS
v_total_marks INT := 0;
v_average_marks NUMBER := 0;
v_count INT := 0;
BEGIN
FOR rec IN (SELECT total FROM mark_details) LOOP
v_total_marks := v_total_marks + rec.total;
v_count := v_count + 1;
END LOOP;

IF v_count > 0 THEN


v_average_marks := v_total_marks / v_count;
END IF;

DBMS_OUTPUT.PUT_LINE('Total Marks: ' || v_total_marks);


DBMS_OUTPUT.PUT_LINE('Average Marks: ' || v_average_marks);
END;
/

-- To execute the procedure and see the output


BEGIN
calculate_marks;
END;
/

Sample Output
yaml
Copy code
Total Marks: 765
Average Marks: 255.00
14.Employee (Empno,Ename, Job,MgrId, DoB,DoJ,
Sal,Comm,Deptno) Department (Dname,Deptno,Dloc) (a)
Display the Emp no, name, salary and experience of each
employee ordered by salary (highest to lowest) (b) List
the names of the employee working for “Marketing”
Department. (c) List the names of the employees born in
the current month. (d) Write a PL/SQL function to display
the details of the employee when Employee no given as
input.

Step 1: Create the Tables


sql
Copy code
CREATE TABLE Employee (
Empno INT PRIMARY KEY,
Ename VARCHAR(100),
Job VARCHAR(50),
MgrId INT,
DoB DATE,
DoJ DATE,
Sal DECIMAL(10, 2),
Comm DECIMAL(10, 2),
Deptno INT
);

CREATE TABLE Department (


Dname VARCHAR(100),
Deptno INT PRIMARY KEY,
Dloc VARCHAR(100)
);

Sample Data Insertion


Let’s add some sample data to the tables.
sql
Copy code
-- Inserting data into Department
INSERT INTO Department (Dname, Deptno, Dloc) VALUES
('Marketing', 1, 'New York'),
('Sales', 2, 'Los Angeles'),
('HR', 3, 'Chicago'),
('IT', 4, 'San Francisco');

-- Inserting data into Employee


INSERT INTO Employee (Empno, Ename, Job, MgrId, DoB, DoJ, Sal, Comm, Deptno)
VALUES
(1, 'Alice Johnson', 'Manager', NULL, TO_DATE('1985-06-15', 'YYYY-MM-DD'),
TO_DATE('2010-01-10', 'YYYY-MM-DD'), 90000, 5000, 1),
(2, 'Bob Smith', 'Salesperson', 1, TO_DATE('1990-01-20', 'YYYY-MM-DD'),
TO_DATE('2015-03-25', 'YYYY-MM-DD'), 60000, 3000, 2),
(3, 'Carol White', 'HR Executive', 1, TO_DATE('1992-03-30', 'YYYY-MM-DD'),
TO_DATE('2017-05-15', 'YYYY-MM-DD'), 50000, 2000, 3),
(4, 'David Brown', 'IT Specialist', 1, TO_DATE('1988-04-05', 'YYYY-MM-DD'),
TO_DATE('2019-07-01', 'YYYY-MM-DD'), 70000, 3500, 4),
(5, 'Eve Black', 'Marketing Executive', 1, TO_DATE('1995-05-25', 'YYYY-MM-DD'),
TO_DATE('2020-09-15', 'YYYY-MM-DD'), 55000, 2500, 1);

a) Display the Emp no, Name, Salary, and Experience of Each Employee
Ordered by Salary (Highest to Lowest)
To calculate the experience, we can use the SYSDATE to find the difference between the joining
date and the current date.
sql
Copy code
SELECT Empno, Ename, Sal,
TRUNC(MONTHS_BETWEEN(SYSDATE, DoJ)) AS Experience
FROM Employee
ORDER BY Sal DESC;

Sample Output
Empno Ename Sal Experience
1 Alice Johnson 90000 168
4 David Brown 70000 56
2 Bob Smith 60000 106
5 Eve Black 55000 26
3 Carol White 50000 64

b) List the Names of the Employees Working for the “Marketing” Department
sql
Copy code
SELECT E.Ename
FROM Employee E
JOIN Department D ON E.Deptno = D.Deptno
WHERE D.Dname = 'Marketing';

Sample Output
Ename
Alice Johnson
Eve Black

c) List the Names of the Employees Born in the Current Month


sql
Copy code
SELECT Ename
FROM Employee
WHERE EXTRACT(MONTH FROM DoB) = EXTRACT(MONTH FROM SYSDATE)
AND EXTRACT(YEAR FROM DoB) <= EXTRACT(YEAR FROM SYSDATE); -- To ensure they
were born in a previous year

Sample Output (Assuming the current month is November)


Ename
Alice Johnson
Bob Smith
d) Write a PL/SQL Function to Display the Details of the Employee When
Employee No Given as Input
Here’s a PL/SQL function that retrieves employee details based on the employee number.
sql
Copy code
CREATE OR REPLACE FUNCTION get_employee_details(p_empno IN INT) RETURN VARCHAR2
IS
v_details VARCHAR2(400);
v_name VARCHAR2(100);
v_job VARCHAR2(50);
v_dob DATE;
v_doj DATE;
v_sal DECIMAL(10, 2);
v_comm DECIMAL(10, 2);
v_deptno INT;
BEGIN
SELECT Ename, Job, DoB, DoJ, Sal, Comm, Deptno
INTO v_name, v_job, v_dob, v_doj, v_sal, v_comm, v_deptno
FROM Employee
WHERE Empno = p_empno;

v_details := 'Employee No: ' || p_empno || ', Name: ' || v_name || ', Job: '
|| v_job ||
', DOB: ' || TO_CHAR(v_dob, 'YYYY-MM-DD') || ', DOJ: ' ||
TO_CHAR(v_doj, 'YYYY-MM-DD') ||
', Salary: ' || v_sal || ', Commission: ' || v_comm || ', Dept
No: ' || v_deptno;

RETURN v_details;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 'No employee found with the given employee number.';
WHEN OTHERS THEN
RETURN 'Error: ' || SQLERRM;
END;
/

Sample Usage
To execute the function and display the details of an employee with Empno 1:
sql
Copy code
DECLARE
emp_details VARCHAR2(400);
BEGIN
emp_details := get_employee_details(1);
DBMS_OUTPUT.PUT_LINE(emp_details);
END;
/

Sample Output
yaml
Copy code
Employee No: 1, Name: Alice Johnson, Job: Manager, DOB: 1985-06-15, DOJ: 2010-
01-10, Salary: 90000, Commiss
15. Write the Query statement for the following a. Create a
Student table (Regno, name, dept) and populate with data. b.
Create a view for CSE dept with the details of students of CSE
dept. c. Implement TCL commands with student table. d.Write a
PL/SQL program to find the details of the student when regno is
given as input.

a. Create a Student Table and Populate with Data


sql
Copy code
CREATE TABLE Student (
Regno INT PRIMARY KEY,
Name VARCHAR(100),
Dept VARCHAR(50)
);

-- Inserting data into Student table


INSERT INTO Student (Regno, Name, Dept) VALUES
(1, 'Alice Johnson', 'CSE'),
(2, 'Bob Smith', 'ECE'),
(3, 'Carol White', 'CSE'),
(4, 'David Brown', 'ME'),
(5, 'Eve Black', 'CSE');

b. Create a View for CSE Dept with the Details of Students of CSE Dept
sql
Copy code
CREATE VIEW CSE_Students AS
SELECT *
FROM Student
WHERE Dept = 'CSE';

c. Implement TCL Commands with the Student Table


sql
Copy code
-- Transaction Control Language (TCL) Commands

-- COMMIT example
COMMIT; -- Commit the current transaction

-- ROLLBACK example
ROLLBACK; -- Rollback the current transaction

-- SAVEPOINT example
SAVEPOINT before_insertion;

-- Inserting additional students as an example


INSERT INTO Student (Regno, Name, Dept) VALUES (6, 'Frank Green', 'CSE');
INSERT INTO Student (Regno, Name, Dept) VALUES (7, 'Grace Lee', 'ECE');

-- Rollback to savepoint if needed


ROLLBACK TO before_insertion; -- This will undo the last two insertions
d. Write a PL/SQL Program to Find the Details of the Student When Regno is Given as Input
sql
Copy code
CREATE OR REPLACE FUNCTION get_student_details(p_regno IN INT) RETURN VARCHAR2
IS
v_details VARCHAR2(200);
v_name VARCHAR2(100);
v_dept VARCHAR2(50);
BEGIN
SELECT Name, Dept
INTO v_name, v_dept
FROM Student
WHERE Regno = p_regno;

v_details := 'Regno: ' || p_regno || ', Name: ' || v_name || ', Dept: ' ||
v_dept;

RETURN v_details;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 'No student found with the given registration number.';
WHEN OTHERS THEN
RETURN 'Error: ' || SQLERRM;
END;
/

-- To execute the function and see the output


DECLARE
student_details VARCHAR2(200);
BEGIN
student_details := get_student_details(1);
DBMS_OUTPUT.PUT_LINE(student_details);
END;
/

Sample Output
yaml
Copy code
Regno: 1, Name: Alice Johnson, Dept: CSE
16. Create a database for Placement and Training cell.
Stud_details(regno, name, dept, percentage)
Company(companyID,name, noOfVacancy) Training_Details(CourseID,
name, Trainer) Placed(regno, companyID,minSal) i List the students
who are eligible for recruitment in a particular company. ii
Display the student who has been placed with highest salary iii
Develop a PL/SQL exception that provides an alternate for not
eligible students. iv Write a PL/SQL program to print the
factorial of given number

Create Tables for Placement and Training Cell


sql
Copy code
CREATE TABLE Stud_details (
Regno INT PRIMARY KEY,
Name VARCHAR(100),
Dept VARCHAR(50),
Percentage DECIMAL(5, 2)
);

CREATE TABLE Company (


CompanyID INT PRIMARY KEY,
Name VARCHAR(100),
NoOfVacancy INT
);

CREATE TABLE Training_Details (


CourseID INT PRIMARY KEY,
Name VARCHAR(100),
Trainer VARCHAR(100)
);

CREATE TABLE Placed (


Regno INT,
CompanyID INT,
MinSal DECIMAL(10, 2),
FOREIGN KEY (Regno) REFERENCES Stud_details(Regno),
FOREIGN KEY (CompanyID) REFERENCES Company(CompanyID)
);

Sample Data Insertion


sql
Copy code
-- Inserting data into Stud_details
INSERT INTO Stud_details (Regno, Name, Dept, Percentage) VALUES
(1, 'Alice Johnson', 'CSE', 85.00),
(2, 'Bob Smith', 'ECE', 78.00),
(3, 'Carol White', 'CSE', 90.00),
(4, 'David Brown', 'ME', 76.50),
(5, 'Eve Black', 'CSE', 92.00);

-- Inserting data into Company


INSERT INTO Company (CompanyID, Name, NoOfVacancy) VALUES
(1, 'Tech Solutions', 5),
(2, 'Innovate Corp', 3),
(3, 'Future Tech', 7);
-- Inserting data into Placed
INSERT INTO Placed (Regno, CompanyID, MinSal) VALUES
(1, 1, 60000),
(3, 2, 65000),
(5, 3, 70000);

i. List the Students Who Are Eligible for Recruitment in a Particular Company
sql
Copy code
SELECT S.Name
FROM Stud_details S
JOIN Company C ON S.Percentage >= 75
WHERE C.CompanyID = 1; -- Change the company ID as needed

Sample Output
Name
Alice Johnson
Carol White
Eve Black
ii. Display the Student Who Has Been Placed with Highest Salary
sql
Copy code
SELECT S.Name, P.MinSal
FROM Stud_details S
JOIN Placed P ON S.Regno = P.Regno
ORDER BY P.MinSal DESC
FETCH FIRST 1 ROW ONLY;

Sample Output
Name MinSal
Eve Black 70000
iii. Develop a PL/SQL Exception that Provides an Alternate for Not Eligible Students
sql
Copy code
CREATE OR REPLACE PROCEDURE check_student_eligibility(p_regno IN INT) AS
v_percentage DECIMAL(5, 2);
BEGIN
SELECT Percentage INTO v_percentage
FROM Stud_details
WHERE Regno = p_regno;

IF v_percentage < 75 THEN


RAISE_APPLICATION_ERROR(-20001, 'Student not eligible for
recruitment.');
ELSE
DBMS_OUTPUT.PUT_LINE('Student is eligible for recruitment.');
END IF;

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No student found with the given registration
number.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
/

-- To execute the procedure


BEGIN
check_student_eligibility(2); -- Change to test different regnos
END;
/

Sample Output
rust
Copy code
Student not eligible for recruitment.

iv. Write a PL/SQL Program to Print the Factorial of a Given Number


sql
Copy code
CREATE OR REPLACE FUNCTION factorial(n IN INT) RETURN INT IS
v_result INT := 1;
BEGIN
FOR i IN 1..n LOOP
v_result := v_result * i;
END LOOP;
RETURN v_result;
END;
/

-- To execute the factorial function


DECLARE
num INT := 5; -- Change to compute factorial of different numbers
fact INT;
BEGIN
fact := factorial(num);
DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is ' || fact);
END;
/

Sample Output
csharp
Copy code
Factorial of 5 is 120
17. Create a database for the following tables. Hostel (hno,
hname, type [boys/girls]) Menu (hno, day, breakfast, lunch,
dinner) Warden (wname, qual, hno) Student (sid, sname, gender,
year, hno)
i. Display the total number of girls and boys hostel in the
college.
ii. Display the menu in the hostel ‘x’ on Tuesday.
iii. Display the number of wardens for each hostel.II.
iv. Write a PL/SQL program to print given number is Prime or not.

Create Tables for the Hostel Database


sql
Copy code
CREATE TABLE Hostel (
Hno INT PRIMARY KEY,
Hname VARCHAR(100),
Type VARCHAR(10) CHECK (Type IN ('boys', 'girls'))
);

CREATE TABLE Menu (


Hno INT,
Day VARCHAR(10),
Breakfast VARCHAR(100),
Lunch VARCHAR(100),
Dinner VARCHAR(100),
FOREIGN KEY (Hno) REFERENCES Hostel(Hno)
);

CREATE TABLE Warden (


Wname VARCHAR(100),
Qualification VARCHAR(100),
Hno INT,
FOREIGN KEY (Hno) REFERENCES Hostel(Hno)
);

CREATE TABLE Student (


Sid INT PRIMARY KEY,
Sname VARCHAR(100),
Gender VARCHAR(10),
Year INT,
Hno INT,
FOREIGN KEY (Hno) REFERENCES Hostel(Hno)
);

Sample Data Insertion


sql
Copy code
-- Inserting data into Hostel table
INSERT INTO Hostel (Hno, Hname, Type) VALUES
(1, 'Boys Hostel A', 'boys'),
(2, 'Girls Hostel A', 'girls'),
(3, 'Boys Hostel B', 'boys'),
(4, 'Girls Hostel B', 'girls');

-- Inserting data into Menu table


INSERT INTO Menu (Hno, Day, Breakfast, Lunch, Dinner) VALUES
(1, 'Tuesday', 'Pancakes', 'Chicken Curry', 'Pasta'),
(2, 'Tuesday', 'Fruit Salad', 'Vegetable Curry', 'Rice'),
(3, 'Tuesday', 'Omelette', 'Fish Curry', 'Salad'),
(4, 'Tuesday', 'Cereal', 'Dal', 'Chapati');

-- Inserting data into Warden table


INSERT INTO Warden (Wname, Qualification, Hno) VALUES
('John Doe', 'M.Sc', 1),
('Jane Smith', 'Ph.D', 2),
('Emily Davis', 'M.A', 3),
('Michael Brown', 'M.Sc', 4);

-- Inserting data into Student table


INSERT INTO Student (Sid, Sname, Gender, Year, Hno) VALUES
(1, 'Alice', 'Female', 2, 2),
(2, 'Bob', 'Male', 1, 1),
(3, 'Carol', 'Female', 3, 4),
(4, 'David', 'Male', 1, 3),
(5, 'Eve', 'Female', 2, 2);

i. Display the Total Number of Girls and Boys Hostels in the College
sql
Copy code
SELECT Type, COUNT(*) AS Total_Hostels
FROM Hostel
GROUP BY Type;

Sample Output
Type Total_Hostels
boys 2
girls 2
ii. Display the Menu in the Hostel ‘x’ on Tuesday
sql
Copy code
-- Replace 'x' with the hostel number you want to query, for example, 2.
SELECT *
FROM Menu
WHERE Hno = 2 AND Day = 'Tuesday';

Sample Output
Hno Day Breakfast Lunch Dinner
2 Tuesday Fruit Salad Vegetable Curry Rice
iii. Display the Number of Wardens for Each Hostel
sql
Copy code
SELECT Hno, COUNT(*) AS Number_of_Wardens
FROM Warden
GROUP BY Hno;

Sample Output
Hno Number_of_Wardens
1 1
2 1
3 1
4 1
iv. Write a PL/SQL Program to Print Given Number is Prime or Not
sql
Copy code
CREATE OR REPLACE FUNCTION is_prime(n IN INT) RETURN VARCHAR2 IS
v_is_prime BOOLEAN := TRUE;
BEGIN
IF n <= 1 THEN
RETURN n || ' is not a prime number.';
END IF;

FOR i IN 2..FLOOR(SQRT(n)) LOOP


IF MOD(n, i) = 0 THEN
v_is_prime := FALSE;
EXIT;
END IF;
END LOOP;

IF v_is_prime THEN
RETURN n || ' is a prime number.';
ELSE
RETURN n || ' is not a prime number.';
END IF;
END;
/

-- To execute the function


DECLARE
result VARCHAR2(50);
BEGIN
result := is_prime(11); -- Change to test different numbers
DBMS_OUTPUT.PUT_LINE(result);
END;
/

Sample Output
csharp
Copy code
11 is a prime number.
18. Consider the following database of student enrollment in
courses and books adopted for that course. STUDENT(regno, name,
major, bdate) COURSE(courseno, cname, dept) ENROLL(regno,
courseno, sem, marks)
i. Display the total number of students register for more than two
courses in a department specified.
ii. Display the students who have secured the highest mark in each
course
iii. List the youngest student of each course in all departments.
iv. Develop PL/SQL program that selects marks of a particular
student in a specified semester.

Create Tables for the Student Enrollment Database


sql
Copy code
CREATE TABLE STUDENT (
Regno INT PRIMARY KEY,
Name VARCHAR(100),
Major VARCHAR(100),
Bdate DATE
);

CREATE TABLE COURSE (


Courseno INT PRIMARY KEY,
Cname VARCHAR(100),
Dept VARCHAR(100)
);

CREATE TABLE ENROLL (


Regno INT,
Courseno INT,
Sem INT,
Marks DECIMAL(5, 2),
FOREIGN KEY (Regno) REFERENCES STUDENT(Regno),
FOREIGN KEY (Courseno) REFERENCES COURSE(Courseno)
);

Sample Data Insertion


sql
Copy code
-- Inserting data into STUDENT table
INSERT INTO STUDENT (Regno, Name, Major, Bdate) VALUES
(1, 'Alice', 'CSE', TO_DATE('2001-05-10', 'YYYY-MM-DD')),
(2, 'Bob', 'ECE', TO_DATE('2000-08-15', 'YYYY-MM-DD')),
(3, 'Carol', 'CSE', TO_DATE('2002-01-20', 'YYYY-MM-DD')),
(4, 'David', 'ME', TO_DATE('1999-12-30', 'YYYY-MM-DD')),
(5, 'Eve', 'CSE', TO_DATE('2001-07-25', 'YYYY-MM-DD'));

-- Inserting data into COURSE table


INSERT INTO COURSE (Courseno, Cname, Dept) VALUES
(101, 'Database Systems', 'CSE'),
(102, 'Data Structures', 'CSE'),
(201, 'Microprocessors', 'ECE');
-- Inserting data into ENROLL table
INSERT INTO ENROLL (Regno, Courseno, Sem, Marks) VALUES
(1, 101, 1, 95),
(1, 102, 1, 90),
(2, 201, 1, 85),
(3, 101, 1, 88),
(3, 102, 1, 91),
(4, 101, 1, 80),
(5, 102, 1, 76);

i. Display the Total Number of Students Registered for More Than Two Courses in a Specified
Department
sql
Copy code
SELECT S.Major, COUNT(S.Regno) AS Total_Students
FROM STUDENT S
JOIN ENROLL E ON S.Regno = E.Regno
JOIN COURSE C ON E.Courseno = C.Courseno
WHERE C.Dept = 'CSE'
GROUP BY S.Major
HAVING COUNT(E.Courseno) > 2;

Sample Output
Major Total_Students
CSE 1
ii. Display the Students Who Have Secured the Highest Mark in Each Course
sql
Copy code
SELECT E.Courseno, S.Name, MAX(E.Marks) AS Highest_Mark
FROM ENROLL E
JOIN STUDENT S ON E.Regno = S.Regno
GROUP BY E.Courseno, S.Name
HAVING MAX(E.Marks) = E.Marks;

Sample Output
Courseno Name Highest_Mark
101 Alice 95
102 Carol 91
iii. List the Youngest Student of Each Course in All Departments
sql
Copy code
SELECT C.Courseno, S.Name, S.Bdate
FROM STUDENT S
JOIN ENROLL E ON S.Regno = E.Regno
JOIN COURSE C ON E.Courseno = C.Courseno
WHERE S.Bdate = (
SELECT MAX(Bdate)
FROM STUDENT
WHERE Regno IN (SELECT Regno FROM ENROLL WHERE Courseno = C.Courseno)
);
Sample Output
Courseno Name Bdate
101 Carol 2002-01-20
102 Alice 2001-05-10
iv. Develop PL/SQL Program That Selects Marks of a Particular Student in a Specified
Semester
sql
Copy code
CREATE OR REPLACE FUNCTION get_student_marks(p_regno IN INT, p_sem IN INT)
RETURN VARCHAR2 IS
v_marks DECIMAL(5, 2);
BEGIN
SELECT Marks INTO v_marks
FROM ENROLL
WHERE Regno = p_regno AND Sem = p_sem;

RETURN 'Marks for student ' || p_regno || ' in semester ' || p_sem || ' is '
|| v_marks;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 'No marks found for the specified student and semester.';
WHEN OTHERS THEN
RETURN 'Error: ' || SQLERRM;
END;
/

-- To execute the function


DECLARE
marks_info VARCHAR2(100);
BEGIN
marks_info := get_student_marks(1, 1); -- Change to test different regnos
and semesters
DBMS_OUTPUT.PUT_LINE(marks_info);
END;
/

Sample Output
csharp
Copy code
Marks for student 1 in semester 1 is 90
19. Create a database for Placement and Training cell.
Stud_details(regno, name, dept, percentage)
Company(companyID,name, noOfVacancy) Training_Details(CourseID,
name, Trainer) Placed(regno, companyID,minSal) v List the students
who are eligible for recruitment in a particular company. vi
Display the student who has been placed with highest salary vii
Develop a PL/SQL exception that provides an alternate for not
eligible students. viii Write a PL/SQL program to print the
factorial of given number.

Part 19: Placement and Training Cell Database


Create Tables for the Placement and Training Cell Database
sql
Copy code
CREATE TABLE Stud_details (
Regno INT PRIMARY KEY,
Name VARCHAR(100),
Dept VARCHAR(100),
Percentage DECIMAL(5, 2)
);

CREATE TABLE Company (


CompanyID INT PRIMARY KEY,
Name VARCHAR(100),
NoOfVacancy INT
);

CREATE TABLE Training_Details (


CourseID INT PRIMARY KEY,
Name VARCHAR(100),
Trainer VARCHAR(100)
);

CREATE TABLE Placed (


Regno INT,
CompanyID INT,
MinSal DECIMAL(10, 2),
PRIMARY KEY (Regno, CompanyID),
FOREIGN KEY (Regno) REFERENCES Stud_details(Regno),
FOREIGN KEY (CompanyID) REFERENCES Company(CompanyID)
);

Sample Data Insertion


sql
Copy code
-- Inserting data into Stud_details
INSERT INTO Stud_details (Regno, Name, Dept, Percentage) VALUES
(1, 'Alice', 'CSE', 85.5),
(2, 'Bob', 'ECE', 90.0),
(3, 'Carol', 'ME', 75.0),
(4, 'David', 'CSE', 65.0),
(5, 'Eve', 'CSE', 92.0);
-- Inserting data into Company
INSERT INTO Company (CompanyID, Name, NoOfVacancy) VALUES
(1, 'TechCorp', 2),
(2, 'InnoSoft', 3),
(3, 'WebSolutions', 1);

-- Inserting data into Training_Details


INSERT INTO Training_Details (CourseID, Name, Trainer) VALUES
(101, 'Java Programming', 'John Doe'),
(102, 'Data Science', 'Jane Smith');

-- Inserting data into Placed


INSERT INTO Placed (Regno, CompanyID, MinSal) VALUES
(1, 1, 60000),
(2, 1, 70000),
(5, 2, 80000);

v. List the Students Who Are Eligible for Recruitment in a Particular Company
sql
Copy code
-- Assuming a company name is provided, e.g., 'TechCorp'.
SELECT S.Regno, S.Name
FROM Stud_details S
WHERE S.Percentage >= 70 -- Assuming eligibility is based on a percentage
greater than or equal to 70
AND S.Regno NOT IN (SELECT P.Regno FROM Placed P WHERE P.CompanyID = (SELECT
C.CompanyID FROM Company C WHERE C.Name = 'TechCorp'));

Sample Output
Regno Name
3 Carol
vi. Display the Student Who Has Been Placed With Highest Salary
sql
Copy code
SELECT S.Regno, S.Name, P.MinSal
FROM Stud_details S
JOIN Placed P ON S.Regno = P.Regno
ORDER BY P.MinSal DESC
FETCH FIRST 1 ROW ONLY;

Sample Output
Regno Name MinSal
5 Eve 80000
vii. Develop a PL/SQL Exception for Not Eligible Students
sql
Copy code
CREATE OR REPLACE PROCEDURE check_eligibility(p_regno IN INT) IS
v_percentage DECIMAL(5, 2);
v_count INT;
BEGIN
SELECT Percentage INTO v_percentage
FROM Stud_details
WHERE Regno = p_regno;
IF v_percentage < 70 THEN
RAISE_APPLICATION_ERROR(-20001, 'Student ' || p_regno || ' is not
eligible for recruitment.');
ELSE
SELECT COUNT(*) INTO v_count
FROM Placed
WHERE Regno = p_regno;

IF v_count > 0 THEN


DBMS_OUTPUT.PUT_LINE('Student ' || p_regno || ' is already
placed.');
ELSE
DBMS_OUTPUT.PUT_LINE('Student ' || p_regno || ' is eligible for
recruitment.');
END IF;
END;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No student found with registration number: ' ||
p_regno);
END;
/

viii. Write a PL/SQL Program to Print the Factorial of Given Number


sql
Copy code
CREATE OR REPLACE FUNCTION factorial(n IN INT) RETURN INT IS
v_fact INT := 1;
BEGIN
IF n < 0 THEN
RETURN 0; -- Factorial is not defined for negative numbers
ELSIF n = 0 THEN
RETURN 1; -- Factorial of 0 is 1
ELSE
FOR i IN 1..n LOOP
v_fact := v_fact * i;
END LOOP;
RETURN v_fact;
END IF;
END;
/

-- To execute the function


DECLARE
result INT;
BEGIN
result := factorial(5); -- Change to test different numbers
DBMS_OUTPUT.PUT_LINE('Factorial: ' || result);
END;
/

Sample Output
makefile
Copy code
Factorial: 120
20. Consider the following relational schema for a Loan database
application: Customer{Customer_id, Customer_name, Age, phone_no}
Loan{ Loan_id, Amount, Customer_id)} i. Include the constraint on
Loan_id that it starts with letter ‘L’. ii. Display the list of
the customer_ids and total Loan amount taken. iii. Display the
Customer_id and Customer_name who have taken less than two loans
v. Write a PL/SQL program to print the details of the customer
when customerid is given as input

Create Tables for the Loan Database Application


sql
Copy code
CREATE TABLE Customer (
Customer_id INT PRIMARY KEY,
Customer_name VARCHAR(100),
Age INT,
Phone_no VARCHAR(15)
);

CREATE TABLE Loan (


Loan_id VARCHAR(20) PRIMARY KEY CHECK (Loan_id LIKE 'L%'),
Amount DECIMAL(10, 2),
Customer_id INT,
FOREIGN KEY (Customer_id) REFERENCES Customer(Customer_id)
);

Sample Data Insertion


sql
Copy code
-- Inserting data into Customer
INSERT INTO Customer (Customer_id, Customer_name, Age, Phone_no) VALUES
(1, 'Alice', 30, '1234567890'),
(2, 'Bob', 25, '0987654321'),
(3, 'Carol', 35, '1122334455');

-- Inserting data into Loan


INSERT INTO Loan (Loan_id, Amount, Customer_id) VALUES
('L001', 5000, 1),
('L002', 10000, 1),
('L003', 7000, 2);

i. Include the Constraint on Loan_id That It Starts With Letter ‘L’


The constraint is already included in the Loan table definition using the CHECK clause.

ii. Display the List of Customer_ids and Total Loan Amount Taken
sql
Copy code
SELECT Customer_id, SUM(Amount) AS Total_Loan_Amount
FROM Loan
GROUP BY Customer_id;
Sample Output
Customer_id Total_Loan_Amount
1 15000
2 7000
iii. Display the Customer_id and Customer_name Who Have Taken Less Than Two Loans
sql
Copy code
SELECT C.Customer_id, C.Customer_name
FROM Customer C
LEFT JOIN Loan L ON C.Customer_id = L.Customer_id
GROUP BY C.Customer_id, C.Customer_name
HAVING COUNT(L.Loan_id) < 2;

Sample Output
Customer_id Customer_name
2 Bob
iv. Write a PL/SQL Program to Print the Details of the Customer When Customerid is Given
as Input
sql
Copy code
CREATE OR REPLACE PROCEDURE get_customer_details(p_customer_id IN INT) IS
v_name VARCHAR(100);
v_age INT;
v_phone_no VARCHAR(15);
BEGIN
SELECT Customer_name, Age, Phone_no
INTO v_name, v_age, v_phone_no
FROM Customer
WHERE Customer_id = p_customer_id;

DBMS_OUTPUT.PUT_LINE('Customer ID: ' || p_customer_id);


DBMS_OUTPUT.PUT_LINE('Name: ' || v_name);
DBMS_OUTPUT.PUT_LINE('Age: ' || v_age);
DBMS_OUTPUT.PUT_LINE('Phone No: ' || v_phone_no);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No customer found with ID: ' || p_customer_id);
END;
/

-- To execute the procedure


BEGIN
get_customer_details(1); -- Change to test different customer IDs
END;
/

Sample Output
yaml
Copy code
Customer ID: 1
Name: Alice
Age: 30
Phone No: 1234567890
21. Create a Table as workers and the details are { S.No, Name,
Designation, Branch } Perform the following commands: i. Alter the
table by adding a column Salary ii. Alter the table by modifying
the column Name iii. Describe the table employee iv. Copy the
table employee as emp v. Truncate the table vi. Delete the Second
row from the table vii. Drop the table. viii. Write a PL/SQL
program to print the given number is odd or even.
22. Create the following tables student_details{register_no,
student_name, DOB, address, city} mark_details{register_no, mark1,
mark2, mark3, total } i. Display only those rows whose total
ranges between 250 and 300. ii. Drop the table mark_details and
Delete the row whose register_no=161. iii. Display all details
whose names begins with 'a'. iv. Write a PL/SQL program to print
the details of the student when regno is given as input

You might also like