Dbms U2
Dbms U2
DECLARE
v_acc_no NUMBER := 101; -- example account number
v_withdraw_amt NUMBER := 6000; -- example withdrawal amount
v_balance NUMBER;
-- 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)
-- 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
);
-- 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)
);
✅ 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;
✅ 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:
SELECT *
FROM Employee
WHERE salary > 1400
AND branch_name <> 'Kothrud';
procedure borrower
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;
END Return_Book;
/
BEGIN
Return_Book('1', 'DBMS');
Return_Book('2', 'TOC');
END;
/
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
-- 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');
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.
-- 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';
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;
/
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:
Explanation:
● JOINs: We are joining the Customers, Orders, and Order_Items tables to get a
complete view of customer data, orders, and products.
● GROUP BY: The query groups the data by Customer_ID, Customer_Name, and
Customer_City to summarize the information for each customer.
This will display the summarized report showing each customer’s name, city, total amount spent,
and the number of unique products purchased.
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:
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).
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;
Find out the name of customer having either loan or account or both in the
bank
SQL Queries:
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.
● 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.
● 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;
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';
● 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());
● 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.
● A sequence is used to generate unique numbers, typically for primary key values. It
increments by a set value and can be used
34. How does the ORDER BY clause affect the result of an SQL query when
used with ASC and DESC?
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:
● 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.
● 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:
● 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.
● 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.
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:
● 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:
● 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:
● 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:
● 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:
● 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:
● 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.
● 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.
● 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:
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:
● 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:
● 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:
● 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:
● NOT IN: Tests if a value is not present in a specified list or subquery result.
Example:
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.
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;
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.
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.
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.