0% found this document useful (0 votes)
21 views36 pages

Dbms U2

The document contains SQL queries for various operations on database tables, including retrieving product information, customer orders, and employee salaries. It also includes PL/SQL blocks for handling transactions, such as bank withdrawals and book returns, along with triggers for salary management. Additionally, it discusses creating views for summarized reports and handling exceptions in a travel booking system.

Uploaded by

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

Dbms U2

The document contains SQL queries for various operations on database tables, including retrieving product information, customer orders, and employee salaries. It also includes PL/SQL blocks for handling transactions, such as bank withdrawals and book returns, along with triggers for salary management. Additionally, it discusses creating views for summarized reports and handling exceptions in a travel booking system.

Uploaded by

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

1. Consider the following relations.

Products(product_id, product_name, category_id, price)


Categories(category_id, category_name)
Customers(customer_id , customer_name)
Orders(order_id, customer_id , order_date, total_amount)
Write SQL queries for the following.

1. Retrieve All Products with Their Categories and Prices


SELECT
p.product_id,
p.product_name,
c.category_name,
p.price
FROM
Products p
JOIN
Categories c ON p.category_id = c.category_id;

2. Retrieve Products with the Highest Unit Price


SELECT
product_id,
product_name,
price
FROM
Products
WHERE
price = (SELECT MAX(price) FROM Products);

3. Find All Customers Who Have Not Placed Any Orders


SELECT
c.customer_id,
c.customer_name
FROM
Customers c
LEFT JOIN
Orders o ON c.customer_id = o.customer_id
WHERE
o.order_id IS NULL;

4. Find the Most Expensive Product


SELECT
product_id,
product_name,
price
FROM
Products
ORDER BY
price DESC
LIMIT 1;

5. Find Customers and the Total Amount They Have Spent


SELECT
c.customer_id,
c.customer_name,
SUM(o.total_amount) AS total_spent
FROM
Customers c
JOIN
Orders o ON c.customer_id = o.customer_id
GROUP BY
c.customer_id, c.customer_name;

2. Write a Database trigger for following requirements:


Employee salary of last three months is stored in the emp_sal table. emp_sal (emp_no,
sal1,sal2,sal3). Before inserting salary into emp_sal table, if salary of employee in any of
the last three months is greater than Rs. 50,000/- then entry of average salary along with
emp_no needs to be inserted into new table; emp_new(emp_no, avg_sal)

CREATE OR REPLACE TRIGGER trg_before_insert_emp_sal


BEFORE INSERT ON emp_sal
FOR EACH ROW
DECLARE
avg_salary NUMBER(10,2);
BEGIN
-- Check if any of the last 3 salaries > 50000
IF :NEW.sal1 > 50000 OR :NEW.sal2 > 50000 OR :NEW.sal3 > 50000 THEN
-- Calculate average salary
avg_salary := (:NEW.sal1 + :NEW.sal2 + :NEW.sal3) / 3;

-- Insert into emp_new table


INSERT INTO emp_new(emp_no, avg_sal)
VALUES (:NEW.emp_no, avg_salary);
END IF;
END;
/
3. Compare SQL with PL/SQL.
Write a PL/SQL block that simulates a bank withdrawal transaction. If the
withdrawal amount is greater than the available balance in the accounts
table, raise a custom exception INSUFFICIENT_BALANCE. Otherwise,
update the balance and display the remaining amount.

DECLARE
v_acc_no NUMBER := 101; -- example account number
v_withdraw_amt NUMBER := 6000; -- example withdrawal amount
v_balance NUMBER;

-- Define custom exception


INSUFFICIENT_BALANCE EXCEPTION;
BEGIN
-- Fetch current balance
SELECT balance INTO v_balance FROM accounts WHERE acc_no = v_acc_no;

-- Check for sufficient balance


IF v_withdraw_amt > v_balance THEN
RAISE INSUFFICIENT_BALANCE;
ELSE
-- Update balance
UPDATE accounts
SET balance = balance - v_withdraw_amt
WHERE acc_no = v_acc_no;

DBMS_OUTPUT.PUT_LINE('Withdrawal successful. Remaining Balance: ' || (v_balance -


v_withdraw_amt));
END IF;

-- Exception handling
EXCEPTION
WHEN INSUFFICIENT_BALANCE THEN
DBMS_OUTPUT.PUT_LINE('Error: Insufficient balance for withdrawal.');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Error: Account not found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Unexpected error: ' || SQLERRM);
END;
/
4. Consider the following relations with appropriate constraints like primary
key, foreign key, check constrains and not null.
Account(Acc_no, branch_name,balance)
branch(branch_name,branch_city,assets)
customer(cust_name,cust_street,cust_city)
Depositor(cust_name,acc_no)
Loan(loan_no,branch_name,amount)
Borrower(cust_name,loan_no)

✅ 1. Table Definitions with Constraints


-- Branch Table
CREATE TABLE Branch (
branch_name VARCHAR(50) PRIMARY KEY,
branch_city VARCHAR(50) NOT NULL,
assets DECIMAL(12,2) CHECK (assets >= 0)
);

-- Account Table
CREATE TABLE Account (
acc_no INT PRIMARY KEY,
branch_name VARCHAR(50),
balance DECIMAL(10,2) CHECK (balance >= 0),
FOREIGN KEY (branch_name) REFERENCES Branch(branch_name)
);

-- Customer Table
CREATE TABLE Customer (
cust_name VARCHAR(50) PRIMARY KEY,
cust_street VARCHAR(100) NOT NULL,
cust_city VARCHAR(50) NOT NULL
);

-- Depositor Table (Many-to-Many relationship)


CREATE TABLE Depositor (
cust_name VARCHAR(50),
acc_no INT,
PRIMARY KEY (cust_name, acc_no),
FOREIGN KEY (cust_name) REFERENCES Customer(cust_name),
FOREIGN KEY (acc_no) REFERENCES Account(acc_no)
);

-- Loan Table
CREATE TABLE Loan (
loan_no INT PRIMARY KEY,
branch_name VARCHAR(50),
amount DECIMAL(10,2) CHECK (amount >= 0),
FOREIGN KEY (branch_name) REFERENCES Branch(branch_name)
);

-- Borrower Table (Many-to-Many relationship)


CREATE TABLE Borrower (
cust_name VARCHAR(50),
loan_no INT,
PRIMARY KEY (cust_name, loan_no),
FOREIGN KEY (cust_name) REFERENCES Customer(cust_name),
FOREIGN KEY (loan_no) REFERENCES Loan(loan_no)
);

✅ 2. Find all loan numbers for loans made at Akurdi Branch with loan
amount > 12000
SELECT loan_no
FROM Loan
WHERE branch_name = 'Akurdi'
AND amount > 12000;

✅ 3. Delete all loans with loan amount between 1300 and 1500
DELETE FROM Loan
WHERE amount BETWEEN 1300 AND 1500;

✅ 4. Delete all account tuples at every branch located in a specific city


Let’s assume the city is 'Pune'.

DELETE FROM Account


WHERE branch_name IN (
SELECT branch_name
FROM Branch
WHERE branch_city = 'Pune'
);

✅ 5. Find all employees whose salary is greater than 1400 and working
branch is not ‘Kothrud’
🔔 Note: You haven’t mentioned an Employee table in the schema, but assuming
such a table exists:

-- Assuming this structure for employees


-- Employee(emp_id, emp_name, branch_name, salary)

SELECT *
FROM Employee
WHERE salary > 1400
AND branch_name <> 'Kothrud';

✅ 6. Find name, account number, and balance of customers with account


balance ≤ 400
SELECT d.cust_name, a.acc_no, a.balance
FROM Depositor d
JOIN Account a ON d.acc_no = a.acc_no
WHERE a.balance <= 400;

5. Write a PL/SQL block of code for the following requirements:


Schema:
1) Borrower (Rollin, Name, DateofIssue, NameofBook, Status)
2) Fine (Roll_no, Date, Amt)
Accept Roll_no and name of book from user.
Check the number of days (from date of issue), if days are between 15 and
30then fine amount will be Rs. 5 per day. If no. of days> 30, per day fine
will be Rs. 50 per day and for days less than 30, Rs. 5 per day.
After submitting the book, status will be change from I to R. If condition of
fine is true, then details will be stored into fine table.

procedure borrower

CREATE TABLE Borrower (


Rollin VARCHAR2(10) PRIMARY KEY,
Name VARCHAR2(100),
DOI DATE,
NameofBook VARCHAR2(100),
Status CHAR(1) CHECK (Status IN ('I','R'))
);

CREATE TABLE Fine (


Rollin VARCHAR2(10) NOT NULL,
FineDate DATE DEFAULT SYSDATE,
Amt NUMBER(10,2),
FOREIGN KEY (Rollin) REFERENCES Borrower(Rollin)
);

INSERT INTO Borrower VALUES ('1','SHRUTI',SYSDATE- 20,'DBMS','I');


INSERT INTO Borrower VALUES ('2','KOSADA', SYSDATE- 14,'TOC','R');
INSERT INTO Borrower VALUES ('3','ANANYA', SYSDATE - 10,'MO','I');
INSERT INTO Borrower VALUES ('4','DIYA', SYSDATE - 1,'COI','R');
INSERT INTO Borrower VALUES ('5','YASH', SYSDATE - 5,'CHEM','I');

CREATE OR REPLACE PROCEDURE Return_Book (


roll_no_ IN VARCHAR2,
book_name IN VARCHAR2
)
AS
doi DATE;
days NUMBER;
fine NUMBER:=0;
status CHAR(1);
BEGIN
SELECT DOI, Status INTO doi, status
FROM Borrower
WHERE Rollin = roll_no_ AND NameofBook = book_name;

IF status='I' THEN
days:=SYSDATE-doi;

IF days>30 THEN
fine:=(days-30)*50 + (15*5);
ELSIF days>15 THEN
fine:=(days-15) * 5;
END IF;

UPDATE Borrower
SET Status='R'
WHERE Rollin=roll_no_ AND NameofBook=book_name;

IF fine>0 THEN
INSERT INTO Fine (Rollin, FineDate, Amt)
VALUES (roll_no_,SYSDATE,fine);
END IF;

DBMS_OUTPUT.PUT_LINE('Book returned successfully.');


IF fine > 0 THEN
DBMS_OUTPUT.PUT_LINE('Fine Amount: Rs ' || fine);
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE('Book is not issued or already returned.');
END IF;

END Return_Book;
/

BEGIN
Return_Book('1', 'DBMS');
Return_Book('2', 'TOC');
END;
/

SELECT * FROM Fine;

6.Write a PL/SQL code block using parameterized cursor, that will merge the
data available in the mewly created table N_RollCall with the data available
in the table O_Rollcall. If the data in the first table already exist in the second
table then that data should be skipped.
cursor rollcall

CREATE TABLE O_RollCall (


roll_no NUMBER PRIMARY KEY,
name VARCHAR2(50)
);

CREATE TABLE N_RollCall (


roll_no NUMBER,
name VARCHAR2(50)
);

-- Sample data
INSERT INTO O_RollCall VALUES (1, 'Alice');
INSERT INTO N_RollCall VALUES (2, 'Bob');
INSERT INTO N_RollCall VALUES (1, 'Alice');
INSERT INTO N_RollCall VALUES (3, 'Charlie');

-- PL/SQL block using parameterized cursor


DECLARE
CURSOR roll_cursor(rn NUMBER) IS
SELECT roll_no, name FROM N_RollCall WHERE roll_no = rn;
v_roll NUMBER;
v_name VARCHAR2(50);
BEGIN
FOR record IN (SELECT * FROM N_RollCall) LOOP
OPEN roll_cursor(record.roll_no);
FETCH roll_cursor INTO v_roll, v_name;
IF roll_cursor%NOTFOUND THEN
INSERT INTO O_RollCall VALUES (record.roll_no, record.name);
DBMS_OUTPUT.PUT_LINE('Inserted Roll No: ' || record.roll_no);
ELSE
DBMS_OUTPUT.PUT_LINE('Skipped (Duplicate): ' || record.roll_no);
END IF;
CLOSE roll_cursor;
END LOOP;
END;
/

7. Consider the following relations.


Books( Book_ID, Title, Author, Genre, Availability_Status)
Users(User_ID , Name, Address, Email, Phone_Number)
Loan( Loan_ID ,Book_ID User_ID, Issue_Date, Due_Date, Return_Date
and write SQL queries for given

1. Find the total number of books borrowed by each user:


SELECT
U.User_ID,
U.Name,
COUNT(L.Book_ID) AS Total_Books_Borrowed
FROM
Users U
JOIN
Loan L ON U.User_ID = L.User_ID
GROUP BY
U.User_ID, U.Name;

2. Retrieve all books currently on loan along with the user details who
borrowed them:
SELECT
B.Book_ID,
B.Title,
B.Author,
U.User_ID,
U.Name,
U.Email,
L.Issue_Date,
L.Due_Date
FROM
Books B
JOIN
Loan L ON B.Book_ID = L.Book_ID
JOIN
Users U ON L.User_ID = U.User_ID
WHERE
L.Return_Date IS NULL; -- This implies the book hasn't been returned yet

8.
Develop a PL/SQL block to update the status of travel bookings in a Travel
Management System based on customer requests. Handle exceptions related
to data validation, including situations where conflicting booking details or
unavailable travel dates are encountered.

CREATE OR REPLACE PROCEDURE update_booking_status (


p_booking_id IN NUMBER,
p_new_status IN VARCHAR2
)
AS
-- Declare variables
v_customer_id Bookings.Customer_ID%TYPE;
v_travel_date Bookings.Travel_Date%TYPE;
v_conflicts NUMBER := 0;
v_max NUMBER := 0;
v_current NUMBER := 0;

-- Custom exceptions
ex_conflict_booking EXCEPTION;
ex_no_data_found EXCEPTION;
ex_travel_full EXCEPTION;

BEGIN
-- Get customer and travel date
BEGIN
SELECT Customer_ID, Travel_Date
INTO v_customer_id, v_travel_date
FROM Bookings
WHERE Booking_ID = p_booking_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE ex_no_data_found;
END;

-- Check for conflicts (same customer, same travel date, different booking)
BEGIN
SELECT COUNT(*)
INTO v_conflicts
FROM Bookings
WHERE Customer_ID = v_customer_id
AND Travel_Date = v_travel_date
AND Booking_ID != p_booking_id
AND Status = 'Confirmed';

IF v_conflicts > 0 THEN


RAISE ex_conflict_booking;
END IF;
EXCEPTION
WHEN ex_conflict_booking THEN
DBMS_OUTPUT.PUT_LINE('Conflict: Same customer has another booking on this
date.');
RETURN;
END;

-- Check travel capacity (if the travel date is fully booked)


BEGIN
SELECT Max_Bookings, Current_Bookings
INTO v_max, v_current
FROM Travel_Capacity
WHERE Travel_Date = v_travel_date;

IF v_current >= v_max AND p_new_status = 'Confirmed' THEN


RAISE ex_travel_full;
END IF;
EXCEPTION
WHEN ex_travel_full THEN
DBMS_OUTPUT.PUT_LINE('Error: Travel date is fully booked.');
RETURN;
END;

-- Update booking status


UPDATE Bookings
SET Status = p_new_status
WHERE Booking_ID = p_booking_id;

DBMS_OUTPUT.PUT_LINE('Booking status updated successfully.');

EXCEPTION
WHEN ex_no_data_found THEN
DBMS_OUTPUT.PUT_LINE('Error: Booking ID not found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Unexpected error: ' || SQLERRM);
END;
/

9. Design a view that combines data from multiple tables to provide a


summarized report for management. Describe the process of creating and
altering views in SQL.

Designing a View for a Summarized Report in SQL

A view in SQL is a virtual table based on the result of a query. It doesn't store data but provides
a convenient way to aggregate, simplify, and present data from one or more tables. Views are
often used to generate reports or perform complex operations.

Here, let's design a view that summarizes customer data by combining information from multiple
tables. We will use the following tables:

1.​ Customers: Holds customer details.​

2.​ Orders: Holds order information, including amounts.​

3.​ Order_Items: Details of products ordered.​

4.​ Products: Information about the products.​

Objective: Create a view to provide a summarized report for management


that shows the total amount spent by each customer, the number of
products they purchased, and their city.

Step 1: SQL Query to Create the View


CREATE VIEW Customer_Summary_Report AS
SELECT
c.Customer_ID,
c.Customer_Name,
c.Customer_City,
SUM(o.Total_Amount) AS Total_Spent,
COUNT(DISTINCT oi.Product_ID) AS Unique_Products_Purchased
FROM
Customers c
JOIN
Orders o ON c.Customer_ID = o.Customer_ID
JOIN
Order_Items oi ON o.Order_ID = oi.Order_ID
GROUP BY
c.Customer_ID, c.Customer_Name, c.Customer_City;

Explanation:

●​ JOINs: We are joining the Customers, Orders, and Order_Items tables to get a
complete view of customer data, orders, and products.​

●​ SUM(): The SUM(o.Total_Amount) calculates the total amount spent by each


customer.​

●​ COUNT(DISTINCT): The COUNT(DISTINCT oi.Product_ID) counts the number of


unique products purchased by each customer.​

●​ GROUP BY: The query groups the data by Customer_ID, Customer_Name, and
Customer_City to summarize the information for each customer.​

Step 2: Querying the View

Once the view is created, you can use it like a table:

SELECT * FROM Customer_Summary_Report;

This will display the summarized report showing each customer’s name, city, total amount spent,
and the number of unique products purchased.

Step 3: Altering the View

If you need to change the structure or logic of the view, you must drop and recreate it. SQL does
not support direct alterations of views (like adding columns). For example, if you wanted to
include an average amount spent, you would drop the existing view and create a new one:

-- Drop the existing view


DROP VIEW Customer_Summary_Report;

-- Recreate the view with an additional column


CREATE VIEW Customer_Summary_Report AS
SELECT
c.Customer_ID,
c.Customer_Name,
c.Customer_City,
SUM(o.Total_Amount) AS Total_Spent,
COUNT(DISTINCT oi.Product_ID) AS Unique_Products_Purchased,
AVG(o.Total_Amount) AS Average_Spent
FROM
Customers c
JOIN
Orders o ON c.Customer_ID = o.Customer_ID
JOIN
Order_Items oi ON o.Order_ID = oi.Order_ID
GROUP BY
c.Customer_ID, c.Customer_Name, c.Customer_City;

Step 4: Dropping the View

If the view is no longer needed, you can drop it with:

DROP VIEW Customer_Summary_Report;

Conclusion:

●​ Views are virtual tables based on queries that simplify reporting and data retrieval.​

●​ Creating a view involves using a SELECT query to define what data the view should
display.​

●​ Views cannot be altered directly; you need to drop and recreate them if changes are
required.​

●​ Summarized reports can be created using views to provide essential insights from
multiple tables without needing to run complex queries repeatedly.​

10 Write an SQL query to create a sales table with the following columns:
sale_id (primary key, integer), product_id (integer, foreign key from products
table), customer_id (integer, foreign key from customers table), quantity
(integer), sale_date (date).

CREATE TABLE sales (


sale_id INT PRIMARY KEY, -- Primary Key for the sale record
product_id INT, -- Product associated with the sale
customer_id INT, -- Customer who made the purchase
quantity INT, -- Quantity of the product sold
sale_date DATE, -- Date of the sale
FOREIGN KEY (product_id) REFERENCES products(product_id), -- Foreign key from
products table
FOREIGN KEY (customer_id) REFERENCES customers(customer_id) -- Foreign key from
customers table
);

11 Write a query to create a payments table with the following columns:


payment_id (integer, primary key), customer_id (integer, foreign key
referencing the customers table), payment_date (date), amount (decimal,
must be greater than 0), and add a unique constraint on payment_id.
CREATE TABLE payments (
payment_id INT PRIMARY KEY, -- Primary Key for the payment record
customer_id INT, -- Customer making the payment
payment_date DATE, -- Date of the payment
amount DECIMAL(10, 2) CHECK (amount > 0), -- Amount of the payment (must be greater
than 0)
FOREIGN KEY (customer_id) REFERENCES customers(customer_id), -- Foreign key
referencing customers table
CONSTRAINT unique_payment_id UNIQUE (payment_id) -- Unique constraint on
payment_id
);

12,14 Students (Student id, Name, Age, Major)


Courses (CourseID, Title, Credits)
Enrollments (EnrollmentID, StudentID, CourseID)
Write a SQL Query for the following requirements
a. Retrieve the name of students along with the title of the course
they are enrolled in.
b. Update the name of students having student id 101
c. Join courses and enrollments table using left join
D. Retrieve the total no of students enrolled course wise

a. Retrieve the name of students along with the title of the course they are
enrolled in.
SELECT
s.Name AS Student_Name,
c.Title AS Course_Title
FROM
Students s
JOIN
Enrollments e ON s.StudentID = e.StudentID
JOIN
Courses c ON e.CourseID = c.CourseID;

b. Update the name of students having student id 101.


UPDATE Students
SET Name = 'New Student Name'
WHERE StudentID = 101;

c. Join Courses and Enrollments tables using a left join.


SELECT
c.CourseID,
c.Title AS Course_Title,
e.EnrollmentID
FROM
Courses c
LEFT JOIN
Enrollments e ON c.CourseID = e.CourseID;

d. Retrieve the total number of students enrolled course-wise.


SELECT
c.Title AS Course_Title,
COUNT(e.StudentID) AS Total_Students_Enrolled
FROM
Courses c
LEFT JOIN
Enrollments e ON c.CourseID = e.CourseID
GROUP BY
c.Title;

13 Depositor (Acct_no, Cust_amt)


Borrower (Loan_no, Cust_amt)
Depositor table maintains information about customer who have account in
bank and borrower table maintains information about customers having loan
in the bank
Find out the name of customer having only account in the bank
Find out the name of customer having both loan and account the bank

Find out the name of customer having either loan or account or both in the
bank

SQL Queries:

1. Find the name of customer having only an account in the bank.


SELECT d.Cust_amt
FROM Depositor d
LEFT JOIN Borrower b ON d.Cust_amt = b.Cust_amt
WHERE b.Cust_amt IS NULL;

2. Find the name of customer having both loan and account in the bank.
SELECT d.Cust_amt
FROM Depositor d
JOIN Borrower b ON d.Cust_amt = b.Cust_amt;

3. Find the name of customer having either loan or account or both in the bank.
SELECT d.Cust_amt
FROM Depositor d
UNION
SELECT b.Cust_amt
FROM Borrower b;

1. Explain how DDL statements like CREATE and ALTER modify the
structure of a database.

●​ CREATE: Used to create database objects like tables, indexes, or views. It defines the
structure of the table (e.g., columns, types, constraints).​

●​ ALTER: Used to modify the structure of an existing database object, such as adding or
dropping columns, modifying data types, or renaming objects.​

2. Describe the role of SQL operators (arithmetic, comparison, logical) in


filtering data.
●​ Arithmetic operators (e.g., +, -, *, /) perform calculations in queries.​

●​ Comparison operators (e.g., =, !=, <, >, <=, >=) are used to compare values and filter
data based on conditions.​

●​ Logical operators (e.g., AND, OR, NOT) are used to combine multiple conditions and
control how rows are returned based on complex conditions.​

3. How does a JOIN operation differ from a UNION in SQL? Provide an


example.

●​ JOIN: Combines columns from two or more tables based on a related column, allowing
access to data from multiple tables.​

●​ UNION: Combines the result sets of two or more queries and removes duplicate rows.​

Example:

-- JOIN Example
SELECT employees.name, departments.department_name
FROM employees
JOIN departments ON employees.department_id = departments.department_id;

-- UNION Example
SELECT name FROM employees
UNION
SELECT name FROM contractors;

4. Write an SQL DDL statement to create a table named employees with


columns for id, name, position, and salary.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
position VARCHAR(50),
salary DECIMAL(10, 2)
);

5. Write an SQL DML query to update the salary of an employee with id=5 to
70,000.
UPDATE employees
SET salary = 70000
WHERE id = 5;

6. Demonstrate how you would retrieve all rows from the orders table
where the order date is after '2023-01-01' using an appropriate SQL
operator.
SELECT * FROM orders
WHERE order_date > '2023-01-01';

7. Compare and contrast the use of DELETE vs TRUNCATE statements in


SQL. What are the advantages and limitations of each?

●​ DELETE: Removes rows one by one, with the option to filter rows with a WHERE clause.
It can be rolled back.​

●​ TRUNCATE: Removes all rows in a table, cannot be filtered, and is faster but cannot be
rolled back in some databases.​

8. Given two SQL tables employees and departments, how would you
structure a query to list all employees who do not belong to any
department?
SELECT e.name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id
WHERE d.department_id IS NULL;

9. Write a query to retrieve all employees from the employees table where
the salary is greater than 50,000.
SELECT * FROM employees
WHERE salary > 50000;

10. Write a query to retrieve all orders from the orders table where the order
amount is greater than 1000 AND the customer is from 'New York'.
SELECT * FROM orders
WHERE order_amount > 1000 AND customer_city = 'New York';
11. Write a query to calculate the total price of products by adding 10% tax
to the price column in the products table.
SELECT product_id, price, price * 1.10 AS total_price_with_tax
FROM products;

12. Write a query to retrieve all customers whose name starts with the letter
'A' in the customers table.
SELECT * FROM customers
WHERE name LIKE 'A%';

13. Write a query to add a new column email of type VARCHAR to the
employees table.
ALTER TABLE employees
ADD email VARCHAR(100);

14. Write a query to drop the phone_number column from the customers
table.
ALTER TABLE customers
DROP COLUMN phone_number;

15. Write a query to update the salary of an employee with emp_id = 101 in
the employees table to 80,000.
UPDATE employees
SET salary = 80000
WHERE emp_id = 101;

16. Write a query to increase the price of all products in the products table
by 5%.
UPDATE products
SET price = price * 1.05;
17. Write a query to set the status column to 'Inactive' for all customers in
the customers table whose last_purchase_date was more than 1 year ago.
UPDATE customers
SET status = 'Inactive'
WHERE last_purchase_date < CURDATE() - INTERVAL 1 YEAR;

18. Write a query to delete all records from the orders table where the order
amount is less than 100.
DELETE FROM orders
WHERE order_amount < 100;

19. Write a query to remove a customer from the customers table with
customer_id = 5.
DELETE FROM customers
WHERE customer_id = 5;

20. Write a query to calculate the total value of all products in stock by
multiplying price and stock_quantity in the products table.
SELECT SUM(price * stock_quantity) AS total_inventory_value
FROM products;

21. Fetch all customers from the customers table who have an "Active"
status and registered before 2023.
SELECT * FROM customers
WHERE status = 'Active' AND registration_date < '2023-01-01';

22. Write a query to retrieve all products whose names start with "Pro" in
the products table.
SELECT * FROM products
WHERE product_name LIKE 'Pro%';

23. Write a query to fetch all employees whose salaries are between 40,000
and 80,000.
SELECT * FROM employees
WHERE salary BETWEEN 40000 AND 80000;

24. Write a query to retrieve all products from the products table where the
category is either 'Electronics', 'Clothing', or 'Furniture' using the IN
operator.
SELECT * FROM products
WHERE category IN ('Electronics', 'Clothing', 'Furniture');

25. Write a query to retrieve all customers from the customers table who do
not have a phone_number (i.e., the phone_number is NULL).
SELECT * FROM customers
WHERE phone_number IS NULL;

26. Write a query to update the status of customers in the customers table
to "VIP" if their last_purchase_date is within the last 30 days.
UPDATE customers
SET status = 'VIP'
WHERE last_purchase_date >= CURDATE() - INTERVAL 30 DAY;

27. Write a query to retrieve the top 5 most expensive products from the
products table, ordered by price in descending order.
SELECT * FROM products
ORDER BY price DESC
LIMIT 5;

28. Write a query to calculate the total number of orders and the total
amount of sales (total_amount) from the orders table for the current year.
SELECT COUNT(order_id) AS total_orders, SUM(total_amount) AS total_sales
FROM orders
WHERE YEAR(order_date) = YEAR(CURDATE());

29. Explain how an index improves query performance in SQL.

●​ An index speeds up the retrieval of rows from a table by providing a faster search
mechanism. It is like a table of contents for a book, helping to quickly locate data without
scanning the entire table.​

30. Describe how the WHERE clause filters rows in a SELECT query.

●​ The WHERE clause filters rows based on specified conditions, only returning rows that
meet the criteria set in the condition.​

31. How does the GROUP BY clause interact with aggregate functions in
SQL?

●​ The GROUP BY clause groups rows with the same values into summary rows, often
used with aggregate functions (e.g., COUNT(), SUM(), AVG(), MIN(), MAX()) to
perform calculations on each group.​

32. Explain the difference between MIN() and MAX() functions in SQL.

●​ MIN() returns the smallest value in a column.​

●​ MAX() returns the largest value in a column.​

33. Describe the purpose of a sequence in SQL and how it generates


unique values.

●​ A sequence is used to generate unique numbers, typically for primary key values. It
increments by a set value and can be used​

for auto-incrementing columns.

34. How does the ORDER BY clause affect the result of an SQL query when
used with ASC and DESC?

●​ ORDER BY ASC sorts results in ascending order (lowest to highest).​

●​ ORDER BY DESC sorts results in descending order (highest to lowest).​

36. What is the difference between a function and an aggregate function in


SQL?
●​ Function: A regular function operates on individual rows or values. It returns a single
result for each row of the query. Examples include UPPER(), LOWER(), ROUND(), etc.​

●​ Aggregate Function: An aggregate function operates on multiple rows and returns a


single result for the group of rows. Examples include COUNT(), SUM(), AVG(), MIN(),
and MAX().​

37. Explain the purpose of the HAVING clause in SQL. How is it different
from WHERE?

●​ HAVING: It is used to filter groups of rows after aggregation is performed by the GROUP
BY clause. It operates on aggregated data (e.g., sums, counts) and allows you to filter
these aggregated results.​

●​ WHERE: It is used to filter rows before the GROUP BY clause or aggregation takes
place. It operates on individual rows of data.​

Example:

SELECT department, AVG(salary)


FROM employees
GROUP BY department
HAVING AVG(salary) > 50000; -- Filters groups where average salary is greater than 50,000

38. How does an SQL synonym help in managing database objects?

●​ An SQL synonym is an alias for an existing database object (like a table, view, or stored
procedure). It allows you to reference the object using a different name, simplifying
queries and improving flexibility. It also helps in managing changes, as the synonym can
point to a different object without needing to change the queries that use it.​

39. Discuss the role of the DISTINCT keyword in a SELECT statement.

●​ The DISTINCT keyword is used to return only unique (non-duplicate) rows in the result
set. It eliminates duplicate records and ensures that each row in the output is distinct.​

Example:

SELECT DISTINCT department FROM employees;


40. Justify the need for aggregate functions in reporting and analysis of
data in SQL.

●​ Aggregate functions are essential for summarizing and analyzing large datasets. They
allow you to compute important metrics such as totals (SUM()), averages (AVG()),
counts (COUNT()), and extreme values (MIN(), MAX()). These metrics are invaluable in
reporting and business analysis, helping organizations make data-driven decisions.​

41. Evaluate the performance benefits of using indexes on frequently


searched columns versus the cost of maintaining those indexes.

●​ Performance Benefits: Indexes improve query performance by allowing the database


engine to quickly locate the rows that match a query condition, reducing the need for full
table scans.​

●​ Cost: Indexes consume additional disk space and can slow down data modification
operations (e.g., INSERT, UPDATE, DELETE) because the index must be updated
whenever the underlying data changes. Therefore, they should be used on columns that
are frequently searched but not modified often.​

42. Discuss why grouping data with GROUP BY and using aggregate
functions may slow down query performance in large datasets.

●​ Grouping and Aggregation: When dealing with large datasets, the database must
process and group a significant number of rows before applying aggregation functions.
This can be computationally expensive, as it requires sorting or partitioning the data,
which can impact query performance, especially without proper indexes.​

43. Write a query to retrieve the average salary for each department from
the employees table using the GROUP BY clause.
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;

44. Create an SQL query that uses ORDER BY to sort the results of the
products table by price in descending order.
SELECT * FROM products
ORDER BY price DESC;

45. Use the MAX() function to find the highest salary from the employees
table.
SELECT MAX(salary) AS highest_salary
FROM employees;

46. Write an SQL query to count how many customers have placed orders
in the orders table.
SELECT COUNT(DISTINCT customer_id) AS num_customers
FROM orders;

47. Write a query to create an index on the email column in the customers
table.
CREATE INDEX idx_email ON customers(email);

48. Create a sequence in SQL that starts from 1000 and increments by 1.
CREATE SEQUENCE seq_customer_id
START WITH 1000
INCREMENT BY 1;

49. Write an SQL query to display the total sales amount from the orders
table, grouping by customer_id.
SELECT customer_id, SUM(total_amount) AS total_sales
FROM orders
GROUP BY customer_id;

50. Write a query that retrieves the customer_id and total_amount from the
orders table but only for customers whose total_amount exceeds 1,000
using HAVING.
SELECT customer_id, SUM(total_amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING SUM(total_amount) > 1000;
51. Analyze the impact of an index on query performance when querying a
large dataset.

●​ Impact: Indexes significantly improve query performance by speeding up searches on


indexed columns, particularly for large datasets. However, they introduce overhead for
INSERT, UPDATE, and DELETE operations, as the index must be updated each time
data is modified. Proper index design can dramatically improve read-heavy queries, but
careful consideration is needed for write-heavy environments.​

52. How does the DISTINCT keyword affect performance when used with an
aggregate function like COUNT()?

●​ Using DISTINCT with an aggregate function like COUNT() can slow down query
performance because the database has to perform an additional operation to remove
duplicates before applying the aggregation. This is especially noticeable when dealing
with large datasets.​

Example:

SELECT COUNT(DISTINCT product_id) FROM orders;

53. Compare the functionality of ROWNUM vs LIMIT for retrieving a specific


number of rows in SQL.

●​ ROWNUM: It is used in Oracle SQL to limit the number of rows returned by a query, but
it is assigned before any ORDER BY clause is applied, meaning it may not return the
expected rows if sorting is involved.​

●​ LIMIT: Used in MySQL, PostgreSQL, and other SQL databases to specify the number of
rows to return, and it works effectively with ORDER BY to return the first N rows of the
result.​

Example:

SELECT * FROM products LIMIT 5; -- MySQL/PostgreSQL


54. Analyze how grouping works in SQL when using both GROUP BY and
ORDER BY in the same query.

●​ GROUP BY: Groups rows that have the same values into summary rows, like summing
up values or calculating averages for each group.​

●​ ORDER BY: Sorts the result set after the grouping has been done. It does not affect the
grouping process but determines the order in which the results are presented.​

Example:

SELECT department, AVG(salary)


FROM employees
GROUP BY department
ORDER BY AVG(salary) DESC;

55. In what scenarios would you use a sequence instead of an


auto-increment field in SQL?

●​ Sequence: A sequence is useful when you need to generate unique numbers across
multiple tables or need more control over the number sequence (e.g., starting point,
increment value, and caching). Sequences are also more flexible for generating IDs in
situations where an auto-increment field is not suitable, such as in distributed systems
where multiple databases might generate unique IDs independently.​

●​ Auto-increment: It is simpler and more automatic, ideal for generating unique IDs in a
single table, but lacks flexibility compared to sequences.​

56. Evaluate the use of SQL functions like UPPER() and LOWER() when
handling case-sensitive data.

●​ UPPER() and LOWER() functions are useful for converting text to a uniform case,
making it easier to handle case-sensitive data in SQL. These functions are particularly
helpful when performing searches or comparisons on case-sensitive columns in
databases that differentiate between uppercase and lowercase characters. Using these
functions ensures consistency, as it allows for case-insensitive comparisons.​

Example:

SELECT * FROM users WHERE UPPER(username) = 'JOHNDOE';


57. How does the SUM() function handle NULL values, and how does it
differ from COUNT()?

●​ SUM(): The SUM() function ignores NULL values in its calculation. It only sums
non-NULL values.​

●​ COUNT(): COUNT(*) counts all rows, including rows with NULL values, while
COUNT(column_name) counts only non-NULL values in that specific column.​

Example:

SELECT SUM(salary) FROM employees; -- Ignores NULL salaries


SELECT COUNT(salary) FROM employees; -- Counts non-NULL salaries

58. Analyze the difference between COUNT(*) and COUNT(column_name)


when counting rows in SQL.

●​ COUNT(*) counts all rows in the table, including those with NULL values in any column.​

●​ COUNT(column_name) counts only the rows where the specified column has
non-NULL values.​

Example:

SELECT COUNT(*) FROM employees; -- Counts all rows


SELECT COUNT(salary) FROM employees; -- Counts rows with non-NULL salary

59. Discuss the performance implications of using synonyms in a large


database system.

●​ Synonyms: In large databases, synonyms provide an alias for database objects,


simplifying queries and enhancing abstraction. While they don't directly affect
performance, they can improve maintainability and readability. However, frequent use of
synonyms can introduce slight overhead because they add another layer of indirection.
Moreover, if the target object of a synonym changes, it can potentially cause issues if the
synonyms are not updated.​
60. Explain how an SQL view simplifies complex queries.

●​ An SQL view simplifies complex queries by encapsulating them as virtual tables. This
allows for reusability and reduces the need to repeatedly write long or complex SQL
statements. Views can simplify query development, improve consistency, and enhance
security by limiting access to specific data.​

61. Describe how indexes can improve query performance in a database.

●​ Indexes speed up data retrieval by allowing the database to quickly locate rows that
match a given query condition. They reduce the need for full table scans, improving
performance especially on large tables. However, indexes can slow down insert, update,
and delete operations since the index must be maintained with each change.​

62. How does a LEFT JOIN differ from a RIGHT JOIN?

●​ LEFT JOIN: Returns all rows from the left table and the matching rows from the right
table. If there is no match, NULL values are returned for columns from the right table.​

●​ RIGHT JOIN: Returns all rows from the right table and the matching rows from the left
table. If there is no match, NULL values are returned for columns from the left table.​

Example:

SELECT * FROM employees LEFT JOIN departments ON employees.dept_id =


departments.dept_id;
SELECT * FROM employees RIGHT JOIN departments ON employees.dept_id =
departments.dept_id;

63. Explain the difference between UNION and UNION ALL in SQL.

●​ UNION: Combines the results of two queries and removes duplicate rows.​

●​ UNION ALL: Combines the results of two queries without removing duplicates.​

Example:

SELECT first_name FROM employees


UNION
SELECT first_name FROM managers; -- Removes duplicates
SELECT first_name FROM employees
UNION ALL
SELECT first_name FROM managers; -- Keeps duplicates

64. Describe how nested queries work in SQL.

●​ A nested query (or subquery) is a query inside another query. The inner query is
executed first, and its result is passed to the outer query. Nested queries are used to
perform complex searches or aggregations that depend on the result of another query.​

Example:

SELECT first_name FROM employees


WHERE salary > (SELECT AVG(salary) FROM employees);

65. How does the INTERSECT operation work in SQL?

●​ The INTERSECT operation returns the common rows from two or more queries. It only
includes rows that appear in both result sets, eliminating duplicates automatically.​

Example:

SELECT first_name FROM employees


INTERSECT
SELECT first_name FROM managers;

66. Explain the role of EXISTS in a nested query.

●​ EXISTS checks if a subquery returns any rows. It returns TRUE if the subquery returns at
least one row, and FALSE if it returns no rows. It is often used for checking the existence
of data without needing to retrieve specific values.​

Example:

SELECT first_name FROM employees


WHERE EXISTS (SELECT 1 FROM orders WHERE employees.emp_id = orders.emp_id);
67. Describe the purpose of set membership operators like IN and NOT IN.

●​ IN: Tests if a value is present in a specified list or subquery result.​

●​ NOT IN: Tests if a value is not present in a specified list or subquery result.​

Example:

SELECT * FROM employees WHERE department IN ('HR', 'IT');


SELECT * FROM employees WHERE department NOT IN ('HR', 'IT');

68. How does set membership differ from joins when combining data?

●​ Set Membership (IN, NOT IN): Directly compares a column to a set of values, typically
used for filtering rows based on simple conditions or subquery results.​

●​ Joins: Combine rows from two or more tables based on related columns. Joins are used
for retrieving related data from multiple tables, while set membership is typically used for
filtering within one table or comparing values to a set.​

69. Explain the relationship between PL/SQL and procedural programming


concepts.

●​ PL/SQL (Procedural Language/SQL) is Oracle's procedural extension to SQL,


incorporating procedural programming concepts such as variables, loops, conditionals,
exception handling, and functions/procedures. It allows SQL statements to be executed
within a procedural context, facilitating more complex logic and control flow than
standard SQL.​

70. Write an SQL query to create a view called employee_department_view


that joins the employees and departments tables, displaying emp_id,
first_name, dept_name.
CREATE VIEW employee_department_view AS
SELECT e.emp_id, e.first_name, d.dept_name
FROM employees e
JOIN departments d ON e.dept_id = d.dept_id;
71. Create an index on the salary column in the employees table to improve
performance for salary-related queries.
CREATE INDEX idx_salary ON employees(salary);

72. Write a query to update the products table to increase the price of all
products by 10% using an index on the category column.
UPDATE products
SET price = price * 1.10
WHERE category_id IN (SELECT category_id FROM categories WHERE category_name =
'Electronics');

73. Write a query that performs a UNION of two tables, employees and
managers, showing their first names and last names.
SELECT first_name, last_name FROM employees
UNION
SELECT first_name, last_name FROM managers;

74. Write a query using INNER JOIN to fetch the list of all orders along with
the customer details from orders and customers tables.
SELECT o.order_id, o.order_date, c.customer_id, c.customer_name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.customer_id;

75. Create a nested query to find employees from the employees table who
earn more than the average salary.
SELECT first_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

76. Write a query using LEFT JOIN to retrieve all products and their
corresponding orders (if any) from the products and orders tables.
SELECT p.product_id, p.product_name, o.order_id
FROM products p
LEFT JOIN orders o ON p.product_id = o.product_id;
77. Write a nested query to retrieve all customers who have made orders
above $1,000.
SELECT customer_id
FROM orders
WHERE total_amount > 1000;

78. Write a query using the INTERSECT operation to find common


employees between employees and managers based on emp_id.
SELECT emp_id FROM employees
INTERSECT
SELECT emp_id FROM managers;

79. Write an SQL PL/SQL block to print "Hello, World!".


BEGIN
DBMS_OUTPUT.PUT_LINE('Hello, World!');
END;

80. Analyze the benefits of using a view versus writing complex SQL
queries every time data is retrieved.

●​ Views encapsulate complex SQL logic, making it easier to reuse and manage. They
provide a simple, abstract interface to complex data retrieval operations. Using views
improves consistency, simplifies code, and can be more secure by restricting access to
sensitive data. It also helps with maintainability since the logic is centralized in the view
definition.​

81. Compare the performance implications of using indexes on frequently


queried columns versus rarely queried columns.

●​ Indexes on frequently queried columns improve performance significantly by speeding


up query execution. However, indexes on rarely queried columns may not offer a
performance benefit and could add unnecessary overhead for INSERT, UPDATE, and
DELETE operations due to the need to maintain the index.​

82. Analyze the behavior of FULL OUTER JOIN and how it compares to
LEFT JOIN and RIGHT JOIN.
●​ FULL OUTER JOIN returns all rows from both tables, with NULL where there is no
match. In contrast:​

○​ LEFT JOIN returns all rows from the left table and matching rows from the right
table.​

○​ RIGHT JOIN returns all rows​

from the right table and matching rows from the left table.

83. Discuss the difference in performance between UNION and UNION ALL.

●​ UNION requires extra processing to eliminate duplicate rows, which can result in slower
performance, especially with large datasets.​

●​ UNION ALL does not remove duplicates and is faster because it does not require
additional sorting and filtering.​

84. How would the performance of a query change if a nested query is used
instead of a join?

●​ Nested queries (subqueries) can be less efficient than joins because the database may
need to execute the inner query for each row returned by the outer query. Joins typically
allow the database to use indexes efficiently and avoid repeated query executions.​

85. Compare the use of set membership (IN, NOT IN) with joins when
selecting records from related tables.

●​ Set membership (IN) is suitable when filtering data based on simple conditions or when
combining lists of values. Joins are more effective when you need to combine related
data from multiple tables, and are typically more performant when dealing with large
datasets.​

86. How does set membership like IN differ from EXISTS in nested queries?

●​ IN compares a value to a list or result set and returns matches. EXISTS checks if the
subquery returns any rows. EXISTS is generally more efficient in certain cases because
it stops processing once a match is found.​
87. Analyze the impact of using an index on a column with a lot of duplicate
values.

●​ An index on a column with many duplicate values may not significantly improve query
performance. Indexes are most beneficial when they are applied to columns with high
cardinality (i.e., many unique values). If there are many duplicates, the index will have a
larger size but may still offer limited performance improvement.​

88. Compare the syntax and behavior of SQL functions and PL/SQL
procedures.

●​ SQL functions are expressions that can be called in SQL statements to perform
operations (e.g., aggregation, string manipulation). They return a value and are typically
used within SQL queries.​

●​ PL/SQL procedures are blocks of procedural code that can execute multiple SQL
statements. They can include variables, loops, and conditionals. PL/SQL allows for more
complex logic than SQL functions.​

89. Discuss the use cases where INTERSECT would be preferable to a join.

●​ INTERSECT is preferable when you need to find the common rows between two
queries, especially when they involve completely separate datasets. Joins are better
suited for combining related data across tables. Use INTERSECT when you specifically
want to identify overlapping data without combining the tables.​

You might also like