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

DMS - Practice Program List

Uploaded by

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

DMS - Practice Program List

Uploaded by

shrikant.dhende1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Database creation, queries, relationships, and normalization.

1. Student Database Creation

Problem Statement: Create a database for managing student information at a school. The database should
contain the following tables:

 Student: StudentID (Primary Key), FirstName, LastName, DateOfBirth, Address, Phone


 Course: CourseID (Primary Key), CourseName, Credits
 Enrollment: EnrollmentID (Primary Key), StudentID (Foreign Key), CourseID (Foreign Key),
EnrollmentDate

Tasks:

 Create the tables using SQL.


 Insert sample data into the tables.
 Write a query to display the list of students enrolled in a particular course.
 Write a query to find students who are enrolled in more than 2 courses.

2. Library Management System

Problem Statement: Create a database for a library to manage books and borrowers. The database should
contain the following tables:

 Book: BookID (Primary Key), Title, Author, Publisher, YearPublished


 Member: MemberID (Primary Key), FirstName, LastName, Email, Phone
 IssueRecord: IssueID (Primary Key), BookID (Foreign Key), MemberID (Foreign Key), IssueDate,
ReturnDate

Tasks:

 Create the tables using SQL.


 Insert sample data into the tables.
 Write a query to list all books currently issued to members.
 Write a query to find out which books have not been returned yet.

3. Employee and Department Management

Problem Statement: Create a database to manage employee details in an organization. The database should
have the following tables:

 Employee: EmployeeID (Primary Key), FirstName, LastName, DOB, Salary, DepartmentID (Foreign Key)
 Department: DepartmentID (Primary Key), DepartmentName, ManagerID (Foreign Key, references
EmployeeID from Employee)
Tasks:

 Create the tables using SQL.


 Insert sample data into the tables.
 Write a query to list all employees working in a particular department.
 Write a query to find the highest-paid employee in each department.

4. Inventory Management System

Problem Statement: Create a database to manage the inventory of a store. The database should contain the
following tables:

 Product: ProductID (Primary Key), ProductName, Category, Price, StockQuantity


 Supplier: SupplierID (Primary Key), SupplierName, ContactName, Phone, Email
 Purchase: PurchaseID (Primary Key), ProductID (Foreign Key), SupplierID (Foreign Key), Quantity,
PurchaseDate

Tasks:

 Create the tables using SQL.


 Insert sample data into the tables.
 Write a query to display all products with a stock quantity of less than 10.
 Write a query to list the suppliers who have supplied a particular product.

5. Online Shopping Database

Problem Statement: Create a database for an online shopping platform. The database should include the
following tables:

 Customer: CustomerID (Primary Key), FirstName, LastName, Email, Phone, Address


 Product: ProductID (Primary Key), ProductName, Category, Price
 Order: OrderID (Primary Key), CustomerID (Foreign Key), OrderDate
 OrderDetails: OrderDetailID (Primary Key), OrderID (Foreign Key), ProductID (Foreign Key), Quantity

Tasks:

 Create the tables using SQL.


 Insert sample data into the tables.
 Write a query to list all orders placed by a particular customer.
 Write a query to display the total value of orders placed by each customer.

6. Hotel Reservation System

Problem Statement: Create a database for a hotel to manage room bookings. The database should contain the
following tables:
 Room: RoomID (Primary Key), RoomType, Price, Status (e.g., Available, Booked)
 Guest: GuestID (Primary Key), FirstName, LastName, Phone, Email
 Reservation: ReservationID (Primary Key), GuestID (Foreign Key), RoomID (Foreign Key), CheckInDate,
CheckOutDate

Tasks:

 Create the tables using SQL.


 Insert sample data into the tables.
 Write a query to display all reservations for a particular room.
 Write a query to find guests who have stayed for more than 5 days.

7. Sales Database

Problem Statement: Create a database to store sales transactions. The database should have the following
tables:

 SalesPerson: SalesPersonID (Primary Key), FirstName, LastName, Email, Phone


 Product: ProductID (Primary Key), ProductName, Price
 Sale: SaleID (Primary Key), SalesPersonID (Foreign Key), SaleDate, TotalAmount
 SaleDetails: SaleDetailID (Primary Key), SaleID (Foreign Key), ProductID (Foreign Key), Quantity

Tasks:

 Create the tables using SQL.


 Insert sample data into the tables.
 Write a query to list all products sold in a particular sale.
 Write a query to calculate the total sales made by a particular salesperson.

8. Student Grades System

Problem Statement: Create a database to store student grades for various subjects. The database should contain
the following tables:

 Student: StudentID (Primary Key), FirstName, LastName


 Subject: SubjectID (Primary Key), SubjectName
 Grade: GradeID (Primary Key), StudentID (Foreign Key), SubjectID (Foreign Key), Grade

Tasks:

 Create the tables using SQL.


 Insert sample data into the tables.
 Write a query to display the grades of a particular student.
 Write a query to calculate the average grade of a student across all subjects.
Transaction Control Language (TCL) commands

1. Basic Transaction with Commit

Problem Statement: Create a simple transaction to update the salary of an employee in the Employee table.
Use the following details:

 Table: Employee
o EmployeeID (Primary Key), FirstName, LastName, Salary

Tasks:

 Update the salary of an employee (choose any employee).


 Use the COMMIT command to save the transaction.
 Verify that the update has been applied correctly by querying the table.

2. Rollback a Failed Transaction

Problem Statement: You are updating the prices of products in a Product table. However, you made a mistake
in your transaction and want to roll back the changes before committing them. The Product table contains the
following fields:

 Table: Product
o ProductID (Primary Key), ProductName, Price, StockQuantity

Tasks:

 Update the price of a product to an incorrect value.


 Execute the ROLLBACK command to undo the changes.
 Verify that the price remains unchanged by querying the table.

3. Using Savepoint for Partial Rollback

Problem Statement: You are updating the prices of several products. You want to make changes to the
Product table but you want the ability to roll back only part of the transaction if needed. The Product table
contains:

 Table: Product
o ProductID (Primary Key), ProductName, Price, StockQuantity

Tasks:

 Start a transaction to update the prices of at least two products.


 Set a SAVEPOINT after the first update.
 Update the price of the second product.
 If something goes wrong, use ROLLBACK TO SAVEPOINT to undo the second update but keep the first one.
 Use the COMMIT command to save the successful changes.
 Verify the final changes by querying the table.

4. Simulate a Transaction with Multiple Steps

Problem Statement: You are working on a database for an online store. The Order table contains customer
order information, and the OrderDetails table contains details about the products in each order. You need to
simulate a multi-step transaction where you:

 Insert a new order into the Order table.


 Insert related order details into the OrderDetails table.
 If the second insertion fails, roll back the entire transaction.

Tables:

 Order
o OrderID (Primary Key), CustomerID, OrderDate
 OrderDetails
o OrderDetailID (Primary Key), OrderID (Foreign Key), ProductID, Quantity, Price

Tasks:

 Start a transaction.
 Insert a new record into the Order table.
 Insert a new record into the OrderDetails table.
 If an error occurs during the insertion into OrderDetails, roll back the entire transaction using ROLLBACK.
 Commit the transaction if both insertions are successful.

5. Transaction with Nested Savepoints

Problem Statement: You are updating records in a BankAccount table, and you want to simulate a banking
transaction with multiple steps (debit and credit operations). You will use nested SAVEPOINT commands to
ensure the transaction can be rolled back to any specific point in case of failure.

Table: BankAccount

 AccountID (Primary Key), AccountHolderName, Balance

Tasks:

 Start a transaction.
 Update the balance of two bank accounts (e.g., transfer money from one account to another).
 Set a SAVEPOINT after the first update.
 Perform the second update (credit to the second account).
 If an error occurs during the second update, use ROLLBACK TO SAVEPOINT to undo only the second update,
but leave the first update intact.
 Commit the transaction if everything is successful.
6. Transaction Handling with COMMIT and ROLLBACK in Sales Database

Problem Statement: In an online store database, you need to simulate a sales transaction. This involves
updating inventory levels and creating a new sales record. The Product and Sale tables are as follows:

 Product: ProductID (Primary Key), ProductName, StockQuantity


 Sale: SaleID (Primary Key), ProductID (Foreign Key), QuantitySold, SaleDate

Tasks:

 Start a transaction.
 Update the StockQuantity of a product when an item is sold.
 Insert a new record into the Sale table to record the sale.
 If any error occurs while inserting into the Sale table (e.g., not enough stock), use ROLLBACK to undo the entire
transaction.
 Use COMMIT if everything is successful and the sale has been processed correctly.

7. Using Savepoint for Error Handling in a Transfer System

Problem Statement: You are building a database for a money transfer system. A transfer involves updating
two accounts: the sender and the receiver. The Account table has the following fields:

 Account: AccountID (Primary Key), AccountHolderName, Balance

Tasks:

 Start a transaction for transferring money from one account to another.


 Update the balance of the sender account by decreasing the transferred amount.
 Set a SAVEPOINT after the first update.
 Update the balance of the receiver account by increasing the transferred amount.
 If there is a problem with the second update (e.g., insufficient funds in the sender account), roll back to the
savepoint and undo the second update.
 Commit the transaction if everything is successful.

8. Managing Transactions for an Employee Salary Update System

Problem Statement: You are tasked with updating the salaries of employees in a payroll system. You need to
ensure that the transaction is either fully committed or completely rolled back in case of errors. The Employee
table has the following fields:

 Employee: EmployeeID (Primary Key), FirstName, LastName, Salary

Tasks:

 Start a transaction to update the salary of multiple employees.


 Use SAVEPOINT after the first update.
 If an error occurs during the second update, use ROLLBACK TO SAVEPOINT to undo the second update but
leave the first one intact.
 Use COMMIT if all updates are successful.

Arithematic and Logical Operators:


1. Calculate Employee Salary After Bonus

Problem Statement: The Employee table contains the following columns: EmployeeID, FirstName, LastName,
Salary, BonusPercent.

 The Salary is the current salary of the employee.


 The BonusPercent is the percentage of the bonus given to the employee.

Task:

 Write a SQL query to calculate the new salary after adding the bonus to the current salary. The formula
for the new salary is: New Salary=Salary+(Salary×BonusPercent100)\text{New Salary} = \text{Salary}
+ (\text{Salary} \times \frac{\text{BonusPercent}}{100})
 Display EmployeeID, FirstName, LastName, Salary, BonusPercent, and the calculated NewSalary.

2. Discount Calculation for Products

Problem Statement: You are given a Product table with the following columns: ProductID, ProductName,
Price, and DiscountPercent.

Task:

 Write a SQL query to calculate the discounted price for each product using the following formula:
Discounted Price=Price−(Price×DiscountPercent100)\text{Discounted Price} = \text{Price} -
(\text{Price} \times \frac{\text{DiscountPercent}}{100})
 Display ProductID, ProductName, Price, DiscountPercent, and DiscountedPrice.

3. Employee Salary Adjustment

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, Salary.

Task:

 Write a query to increase the salary of all employees by 10% using an arithmetic operator.
 Display the EmployeeID, FirstName, LastName, and the updated Salary.
4. Product Quantity Status

Problem Statement: The Product table contains the following columns: ProductID, ProductName,
StockQuantity, and SoldQuantity.

Task:

 Write a SQL query to calculate the remaining stock for each product. The remaining stock is calculated
as: Remaining Stock=StockQuantity−SoldQuantity\text{Remaining Stock} = \text{StockQuantity} -
\text{SoldQuantity}
 Display ProductID, ProductName, StockQuantity, SoldQuantity, and RemainingStock.

5. Average Marks of Students

Problem Statement: The StudentMarks table contains the following columns: StudentID, Subject,
MarksObtained.

Task:

 Write a SQL query to calculate the average marks obtained by each student.
 Display StudentID, and the AverageMarks for each student.

6. Find Employees in a Salary Range

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a SQL query to find employees whose salary is between 30000 and 50000.
 Use a logical operator to check if the salary is within this range.
 Display EmployeeID, FirstName, LastName, and Salary.

7. Age Grouping of Students

Problem Statement: The Student table contains StudentID, FirstName, LastName, DateOfBirth.

Task:

 Write a query to classify students into two age groups:


o Group 1: Age less than 20
o Group 2: Age 20 or older
 Use the DATEDIFF function or similar to calculate age from DateOfBirth.
 Display StudentID, FirstName, LastName, Age, and the AgeGroup.
8. Sales Tax Calculation

Problem Statement: The Order table contains OrderID, TotalAmount, and TaxRate.

Task:

 Write a SQL query to calculate the sales tax for each order.
 Use the following formula to calculate tax: Sales Tax=TotalAmount×TaxRate100\text{Sales Tax} =
\text{TotalAmount} \times \frac{\text{TaxRate}}{100}
 Display OrderID, TotalAmount, TaxRate, and the calculated SalesTax.

9. Product Availability Based on Stock Level

Problem Statement: The Product table contains ProductID, ProductName, StockQuantity.

Task:

 Write a SQL query to display products with the following conditions:


o If StockQuantity is greater than 50, display "In Stock".
o If StockQuantity is between 20 and 50 (inclusive), display "Low Stock".
o If StockQuantity is less than 20, display "Out of Stock".
 Use the CASE statement and logical operators (AND, OR, NOT).
 Display ProductID, ProductName, StockQuantity, and StockStatus.

10. Find Employees Based on Multiple Conditions

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, Department, and
Salary.

Task:

 Write a SQL query to find employees who belong to the "Sales" department and have a salary greater
than 30000.
 Use a logical operator (AND) to combine the conditions.
 Display EmployeeID, FirstName, LastName, Department, and Salary.

11. Graduation Status of Students

Problem Statement: The Student table contains StudentID, FirstName, LastName, Marks.

Task:

 Write a SQL query to check if students have passed or failed based on their marks.
o If marks are greater than or equal to 50, display "Passed".
o Otherwise, display "Failed".
 Use a CASE statement or logical operators.
 Display StudentID, FirstName, LastName, Marks, and GraduationStatus.

12. Product Price Comparison

Problem Statement: The Product table contains ProductID, ProductName, Price, and DiscountPercent.

Task:

 Write a SQL query to calculate the original price of a product before discount, using the formula:
Original Price=Price1−DiscountPercent100\text{Original Price} = \frac{\text{Price}}{1 -
\frac{\text{DiscountPercent}}{100}}
 Display ProductID, ProductName, Price, DiscountPercent, and the OriginalPrice.

13. Find Top N Employees Based on Salary

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a SQL query to find the top 3 highest-paid employees in the company.
 Display EmployeeID, FirstName, LastName, and Salary.

Here are some simple problem statements related to relational operators in SQL, designed to help diploma
students practice these concepts. Relational operators (such as =, !=, <, >, <=, >=, BETWEEN, IN, LIKE, etc.) are
used to compare values in SQL queries.

1. Find Employees with Specific Salary Range

Problem Statement: The Employee table contains the following columns: EmployeeID, FirstName, LastName,
Salary.

Task:

 Write a SQL query to find employees whose salary is between 30,000 and 50,000.
 Use the BETWEEN operator.
 Display EmployeeID, FirstName, LastName, and Salary.

2. Find Products by Price Range

Problem Statement: The Product table contains the following columns: ProductID, ProductName, Price.
Task:

 Write a SQL query to find all products whose price is greater than or equal to 100 but less than 500.
 Use the >= and < relational operators.
 Display ProductID, ProductName, and Price.

3. Search for Employees Not in a Specific Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, Department.

Task:

 Write a SQL query to find all employees who do not belong to the "Sales" department.
 Use the != (or <>) relational operator.
 Display EmployeeID, FirstName, LastName, and Department.

4. Find Products with Specific Categories

Problem Statement: The Product table contains ProductID, ProductName, Category.

Task:

 Write a SQL query to find products that belong to either the "Electronics" or "Clothing" category.
 Use the IN relational operator.
 Display ProductID, ProductName, and Category.

5. Check Students with Marks Above 75

Problem Statement: The StudentMarks table contains the following columns: StudentID, Subject,
MarksObtained.

Task:

 Write a SQL query to find all students who have obtained marks greater than 75.
 Use the > relational operator.
 Display StudentID, Subject, and MarksObtained.

6. Find Employees in Specific Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Department.

Task:
 Write a SQL query to find all employees who work in the "HR" or "Finance" department.
 Use the IN operator.
 Display EmployeeID, FirstName, LastName, and Department.

7. Find Products Not in Stock

Problem Statement: The Product table contains ProductID, ProductName, and StockQuantity.

Task:

 Write a SQL query to find all products that are currently out of stock (i.e., StockQuantity is 0).
 Use the = relational operator.
 Display ProductID, ProductName, and StockQuantity.

8. Find Employees Earning Above Average Salary

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a SQL query to find all employees whose salary is greater than the average salary of all
employees.
 Use the > relational operator and a subquery.
 Display EmployeeID, FirstName, LastName, and Salary.

9. Find Products Matching a Pattern

Problem Statement: The Product table contains ProductID, ProductName.

Task:

 Write a SQL query to find all products whose name starts with "A" (e.g., "Apple", "Ankle", etc.).
 Use the LIKE operator.
 Display ProductID and ProductName.

10. Find Students with Marks Between 50 and 80

Problem Statement: The StudentMarks table contains StudentID, Subject, and MarksObtained.

Task:

 Write a SQL query to find all students whose marks are between 50 and 80 (inclusive).
 Use the BETWEEN operator.
 Display StudentID, Subject, and MarksObtained.

11. Find Orders with Specific Date Range

Problem Statement: The Order table contains OrderID, OrderDate, and TotalAmount.

Task:

 Write a SQL query to find all orders placed between '2024-01-01' and '2024-12-31'.
 Use the BETWEEN operator for date range filtering.
 Display OrderID, OrderDate, and TotalAmount.

12. Find Products with Price Less Than or Equal to 100

Problem Statement: The Product table contains ProductID, ProductName, and Price.

Task:

 Write a SQL query to find all products with a price less than or equal to 100.
 Use the <= relational operator.
 Display ProductID, ProductName, and Price.

13. Find Employees with First Name Starting with 'A'

Problem Statement: The Employee table contains EmployeeID, FirstName, and LastName.

Task:

 Write a SQL query to find all employees whose first name starts with the letter 'A'.
 Use the LIKE operator with the appropriate pattern.
 Display EmployeeID, FirstName, and LastName.

14. Find Customers Not in Specified Cities

Problem Statement: The Customer table contains CustomerID, FirstName, LastName, City.

Task:

 Write a SQL query to find all customers who are not from the cities "New York" or "Los Angeles".
 Use the NOT IN operator.
 Display CustomerID, FirstName, LastName, and City.
15. Find Products with a Name Ending with 'i'

Problem Statement: The Product table contains ProductID, ProductName.

Task:

 Write a SQL query to find all products whose name ends with the letter "i".
 Use the LIKE operator with the appropriate pattern.
 Display ProductID and ProductName.

16. Check if Employee Exists in a Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Department.

Task:

 Write a SQL query to check if there is any employee in the "IT" department.
 Use the EXISTS operator with a subquery.
 Display a message like "Employee exists in IT department" or "No employees in IT department".

17. Find Orders with Total Amount Greater Than 1000

Problem Statement: The Order table contains OrderID, TotalAmount.

Task:

 Write a SQL query to find all orders with a TotalAmount greater than 1000.
 Use the > relational operator.
 Display OrderID and TotalAmount.

18. Compare Two Dates

Problem Statement: The Order table contains OrderID, OrderDate, and DeliveryDate.

Task:

 Write a SQL query to find all orders where the DeliveryDate is after the OrderDate.
 Use the > relational operator.
 Display OrderID, OrderDate, and DeliveryDate.
1. Find All Unique Products from Two Categories

Problem Statement: The Product table contains the columns: ProductID, ProductName, and Category.

Task:

 Write a SQL query to list all unique products from the categories "Electronics" and "Clothing".
 Use the UNION operator to combine the results.
 Display ProductID and ProductName.

2. Find Common Employees in Two Departments

Problem Statement: The Employee table contains the columns: EmployeeID, FirstName, LastName,
Department.

Task:

 Write a SQL query to find employees who are present in both the "Sales" and "Marketing" departments.
 Use the INTERSECT operator to find employees in both departments.
 Display EmployeeID, FirstName, and LastName.

3. List Products Available in Either of Two Categories

Problem Statement: The Product table contains ProductID, ProductName, and Category.

Task:

 Write a SQL query to find all products that are either in the "Electronics" category or the "Furniture"
category.
 Use the UNION operator to combine the result sets.
 Display ProductID, ProductName, and Category.

4. Find Employees Who Do Not Work in Specific Departments

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Department.

Task:

 Write a SQL query to find all employees who do not work in the "HR" department.
 Use the EXCEPT (or MINUS in some databases) operator.
 Display EmployeeID, FirstName, and LastName.
5. Find Students Who Have Enrolled in All Subjects

Problem Statement: The StudentEnrollment table contains StudentID, SubjectID. The Subject table
contains SubjectID, SubjectName.

Task:

 Write a SQL query to find students who are enrolled in all available subjects.
 Use the INTERSECT operator to compare students enrolled in multiple subjects.
 Display StudentID and SubjectName.

6. List All Employees Who Have Either Sales or Marketing Experience

Problem Statement: The EmployeeExperience table contains EmployeeID, Department.

Task:

 Write a SQL query to find all employees who have experience in either the "Sales" or "Marketing"
department.
 Use the UNION operator to combine the two departments' results.
 Display EmployeeID.

7. Find Customers Who Have Placed Orders in Both January and February

Problem Statement: The Order table contains OrderID, CustomerID, and OrderDate.

Task:

 Write a SQL query to find customers who have placed orders in both January and February.
 Use the INTERSECT operator to find customers who placed orders in both months.
 Display CustomerID.

8. List All Products That Are Either Out of Stock or Discontinued

Problem Statement: The Product table contains ProductID, ProductName, StockQuantity, and Status.

Task:

 Write a SQL query to find all products that are either out of stock (i.e., StockQuantity = 0) or
discontinued (i.e., Status = 'Discontinued').
 Use the UNION operator to combine the two conditions.
 Display ProductID, ProductName, and Status.
9. Find Students Who Have Not Taken a Particular Subject

Problem Statement: The StudentEnrollment table contains StudentID, SubjectID. The Subject table
contains SubjectID, SubjectName.

Task:

 Write a SQL query to find students who have not taken the "Mathematics" subject.
 Use the EXCEPT (or MINUS) operator to find students who haven't enrolled in that subject.
 Display StudentID.

10. List All Employees Who Are in Either HR or IT Department, but Not Both

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Department.

Task:

 Write a SQL query to find all employees who are in the "HR" department or the "IT" department, but
not in both.
 Use the EXCEPT and UNION operators to combine the results and exclude employees in both departments.
 Display EmployeeID, FirstName, LastName, and Department.

11. Find Customers Who Have Placed Orders in Both January and March

Problem Statement: The Order table contains OrderID, CustomerID, and OrderDate.

Task:

 Write a SQL query to find customers who have placed orders in both January and March.
 Use the INTERSECT operator to combine the result sets for both months.
 Display CustomerID.

12. List All Products Except Those in 'Electronics' Category

Problem Statement: The Product table contains ProductID, ProductName, and Category.

Task:

 Write a SQL query to find all products except those in the "Electronics" category.
 Use the EXCEPT (or MINUS) operator to exclude products in that category.
 Display ProductID and ProductName.

13. Find Employees Who Are in Both Sales and Marketing

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Department.

Task:

 Write a SQL query to find employees who work in both the "Sales" and "Marketing" departments.
 Use the INTERSECT operator to find employees who belong to both departments.
 Display EmployeeID, FirstName, and LastName.

14. Find All Customers Who Have Not Placed Any Orders

Problem Statement: The Customer table contains CustomerID, CustomerName, and Phone. The Order table
contains OrderID, CustomerID, and OrderDate.

Task:

 Write a SQL query to find all customers who have not placed any orders.
 Use the EXCEPT (or MINUS) operator to exclude customers who have placed orders.
 Display CustomerID and CustomerName.

15. Find All Products That Are Either In Stock or Discontinued

Problem Statement: The Product table contains ProductID, ProductName, StockQuantity, and Status.

Task:

 Write a SQL query to find all products that are either in stock (i.e., StockQuantity > 0) or discontinued
(i.e., Status = 'Discontinued').
 Use the UNION operator to combine both conditions.
 Display ProductID, ProductName, StockQuantity, and Status.

1. Sort Employees by Salary

Problem Statement: The Employee table contains the following columns: EmployeeID, FirstName, LastName,
Salary.

Task:
 Write a SQL query to find all employees and sort them by their salary in descending order.
 Use the ORDER BY clause to sort by Salary.
 Display EmployeeID, FirstName, LastName, and Salary.

2. Find Total Sales by Each Product

Problem Statement: The Sales table contains ProductID, SaleAmount, and SaleDate.

Task:

 Write a SQL query to find the total sales (SaleAmount) for each ProductID.
 Use the GROUP BY clause to group by ProductID.
 Use the SUM() function to calculate the total sales per product.
 Display ProductID and the total SaleAmount.

3. List Employees in Each Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Department.

Task:

 Write a SQL query to list all employees in each department.


 Use the GROUP BY clause to group by Department.
 Display Department, and the total number of employees in each department.

4. Find Products with Sales Above a Certain Threshold

Problem Statement: The Product table contains ProductID, ProductName, and Price, and the Sales table
contains ProductID and SaleAmount.

Task:

 Write a SQL query to find all products with a total sales amount greater than 10,000.
 Use GROUP BY to group by ProductID and SUM() to calculate total sales.
 Use the HAVING clause to filter out products with total sales below 10,000.
 Display ProductID, ProductName, and total SaleAmount.

5. Find Employees Who Earn Above Average Salary

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a SQL query to find all employees whose salary is greater than the average salary.
 Use the AVG() function to calculate the average salary.
 Use WHERE to filter employees with salary above the average.
 Display EmployeeID, FirstName, LastName, and Salary.

6. Find the Highest and Lowest Salary in Each Department

Problem Statement: The Employee table contains EmployeeID, Department, and Salary.

Task:

 Write a SQL query to find the highest and lowest salary in each department.
 Use GROUP BY to group by Department and the MAX() and MIN() functions to get the highest and lowest
salaries.
 Display Department, MAX(Salary) as HighestSalary, and MIN(Salary) as LowestSalary.

7. Sort Products by Price

Problem Statement: The Product table contains ProductID, ProductName, and Price.

Task:

 Write a SQL query to find all products and sort them by Price in ascending order.
 Use the ORDER BY clause to sort by Price.
 Display ProductID, ProductName, and Price.

8. Find Total Sales in Each Month

Problem Statement: The Sales table contains SaleID, SaleAmount, and SaleDate.

Task:

 Write a SQL query to find the total sales (SaleAmount) for each month.
 Use GROUP BY to group by month (you can use MONTH() function or YEAR() and MONTH() combined).
 Use the SUM() function to get the total sales per month.
 Display the month (e.g., YEAR(SaleDate), MONTH(SaleDate)) and the total SaleAmount.

9. Count the Number of Employees in Each Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Department.

Task:
 Write a SQL query to count the number of employees in each department.
 Use the GROUP BY clause to group by Department.
 Use the COUNT() function to get the number of employees in each department.
 Display Department and the number of employees.

10. Find Orders with Total Amount Greater Than 500

Problem Statement: The Order table contains OrderID, OrderDate, and TotalAmount.

Task:

 Write a SQL query to find orders where the TotalAmount is greater than 500.
 Use the WHERE clause to filter out orders below this threshold.
 Display OrderID, OrderDate, and TotalAmount.

11. Find Employees with the Maximum Salary in Each Department

Problem Statement: The Employee table contains EmployeeID, Department, and Salary.

Task:

 Write a SQL query to find the employee with the highest salary in each department.
 Use GROUP BY to group by Department and MAX() to find the highest salary.
 Display Department, EmployeeID, FirstName, LastName, and Salary.

12. Find Customers Who Have Placed More Than One Order

Problem Statement: The Order table contains OrderID, CustomerID, and OrderDate.

Task:

 Write a SQL query to find customers who have placed more than one order.
 Use GROUP BY to group by CustomerID and HAVING to filter those with more than one order.
 Display CustomerID and the number of orders placed.

13. List Products with Average Price Above 50

Problem Statement: The Product table contains ProductID, ProductName, and Price.

Task:

 Write a SQL query to find products with an average price above 50.
 Use GROUP BY to group products by ProductID and HAVING to filter those with an average price above
50.
 Display ProductID, ProductName, and the average price.

14. Find Total Sales by Each Salesperson

Problem Statement: The Sales table contains SaleID, SalespersonID, and SaleAmount.

Task:

 Write a SQL query to find the total sales (SaleAmount) by each salesperson.
 Use GROUP BY to group by SalespersonID and SUM() to calculate total sales.
 Display SalespersonID and the total SaleAmount.

15. Find Top 5 Highest Paid Employees

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a SQL query to find the top 5 highest-paid employees.


 Use the ORDER BY clause to sort by Salary in descending order and LIMIT to select the top 5.
 Display EmployeeID, FirstName, LastName, and Salary.

Inner Join Problems:

1. List Employees with Their Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, DepartmentID, and
the Department table contains DepartmentID, DepartmentName.

Task:

 Write a SQL query to find all employees and their corresponding department names.
 Use an INNER JOIN between the Employee and Department tables based on DepartmentID.
 Display EmployeeID, FirstName, LastName, and DepartmentName.

2. List Products and Their Sales


Problem Statement: The Product table contains ProductID, ProductName, and CategoryID, and the Sales
table contains SaleID, ProductID, and SaleAmount.

Task:

 Write a SQL query to list all products and the sales they have made.
 Use an INNER JOIN between the Product and Sales tables based on ProductID.
 Display ProductID, ProductName, and SaleAmount.

3. List Students and Their Enrolled Courses

Problem Statement: The Student table contains StudentID, StudentName, and the CourseEnrollment table
contains StudentID, CourseID.

Task:

 Write a SQL query to find all students and the courses they have enrolled in.
 Use an INNER JOIN between the Student and CourseEnrollment tables based on StudentID.
 Display StudentName and CourseID.

4. Find Orders and Corresponding Customers

Problem Statement: The Order table contains OrderID, CustomerID, and OrderDate, and the Customer table
contains CustomerID, CustomerName, and City.

Task:

 Write a SQL query to list all orders with their corresponding customers.
 Use an INNER JOIN between the Order and Customer tables based on CustomerID.
 Display OrderID, CustomerName, and OrderDate.

5. List Employees and Their Projects

Problem Statement: The Employee table contains EmployeeID, EmployeeName, and ProjectID, and the
Project table contains ProjectID, ProjectName.

Task:

 Write a SQL query to find all employees and the projects they are working on.
 Use an INNER JOIN between the Employee and Project tables based on ProjectID.
 Display EmployeeID, EmployeeName, and ProjectName.
Outer Join Problems:

6. Find Employees and Their Departments (Including Unassigned Employees)

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and DepartmentID,
and the Department table contains DepartmentID, DepartmentName.

Task:

 Write a SQL query to find all employees and their department names, including employees who are not
assigned to any department.
 Use a LEFT OUTER JOIN between the Employee and Department tables based on DepartmentID.
 Display EmployeeID, FirstName, LastName, and DepartmentName.

7. List All Products and Their Sales (Including Products with No Sales)

Problem Statement: The Product table contains ProductID, ProductName, and the Sales table contains
SaleID, ProductID, and SaleAmount.

Task:

 Write a SQL query to find all products and their total sales, including products that have not been sold.
 Use a LEFT OUTER JOIN between the Product and Sales tables based on ProductID.
 Display ProductID, ProductName, and SaleAmount.

8. Find All Customers and Their Orders (Including Customers with No Orders)

Problem Statement: The Customer table contains CustomerID, CustomerName, and the Order table contains
OrderID, CustomerID, and OrderDate.

Task:

 Write a SQL query to list all customers and their orders, including customers who have not placed any
orders.
 Use a LEFT OUTER JOIN between the Customer and Order tables based on CustomerID.
 Display CustomerName, OrderID, and OrderDate.

9. List All Students and Their Courses (Including Students with No Enrollment)

Problem Statement: The Student table contains StudentID, StudentName, and the CourseEnrollment table
contains StudentID, CourseID.
Task:

 Write a SQL query to list all students and the courses they are enrolled in, including students who are
not enrolled in any course.
 Use a LEFT OUTER JOIN between the Student and CourseEnrollment tables based on StudentID.
 Display StudentName and CourseID.

10. Find Employees and Their Projects (Including Employees Not Assigned to Any Project)

Problem Statement: The Employee table contains EmployeeID, EmployeeName, and ProjectID, and the
Project table contains ProjectID, ProjectName.

Task:

 Write a SQL query to find all employees and the projects they are working on, including employees who
are not assigned to any project.
 Use a LEFT OUTER JOIN between the Employee and Project tables based on ProjectID.
 Display EmployeeID, EmployeeName, and ProjectName.

Full Outer Join Problems:

11. Find All Employees and All Projects (Even If There’s No Assignment)

Problem Statement: The Employee table contains EmployeeID, EmployeeName, and ProjectID, and the
Project table contains ProjectID, ProjectName.

Task:

 Write a SQL query to list all employees and all projects, even if an employee is not assigned to a project
or if a project has no employees assigned.
 Use a FULL OUTER JOIN between the Employee and Project tables based on ProjectID.
 Display EmployeeID, EmployeeName, and ProjectName.

12. List All Products and All Sales (Even If a Product Has No Sale and Sale Has No Product)

Problem Statement: The Product table contains ProductID, ProductName, and the Sales table contains
SaleID, ProductID, and SaleAmount.

Task:

 Write a SQL query to find all products and all sales, even if a product has no sales or a sale is not linked
to any product.
 Use a FULL OUTER JOIN between the Product and Sales tables based on ProductID.
 Display ProductID, ProductName, and SaleAmount.

13. Find All Customers and Their Orders (Including Customers with No Orders and Orders
with No Customers)

Problem Statement: The Customer table contains CustomerID, CustomerName, and the Order table contains
OrderID, CustomerID, and OrderDate.

Task:

 Write a SQL query to find all customers and their orders, even if a customer has no orders or if an order
is not associated with any customer.
 Use a FULL OUTER JOIN between the Customer and Order tables based on CustomerID.
 Display CustomerName, OrderID, and OrderDate.

14. Find All Employees and Departments (Including Employees with No Department and
Departments with No Employees)

Problem Statement: The Employee table contains EmployeeID, EmployeeName, and DepartmentID, and the
Department table contains DepartmentID, DepartmentName.

Task:

 Write a SQL query to find all employees and departments, even if an employee is not assigned to a
department or a department has no employees.
 Use a FULL OUTER JOIN between the Employee and Department tables based on DepartmentID.
 Display EmployeeID, EmployeeName, and DepartmentName.

1. Create a View for Employee Information

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, DepartmentID, and
Salary.

Task:

 Write a SQL query to create a view called EmployeeInfo that displays the EmployeeID, FirstName,
LastName, and Salary of all employees.
 Ensure the view simplifies accessing employee details without showing the DepartmentID.

2. Create a View for Department-wise Employee Count


Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and DepartmentID,
and the Department table contains DepartmentID, DepartmentName.

Task:

 Write a SQL query to create a view called DepartmentEmployeeCount that shows each department's
name and the total number of employees working in that department.
 Include DepartmentName from the Department table and the count of employees from the Employee
table.
 The view should simplify the reporting of employees per department.

3. Create a View for Orders by Customers

Problem Statement: The Customer table contains CustomerID, CustomerName, and the Order table contains
OrderID, CustomerID, and OrderDate.

Task:

 Write a SQL query to create a view called CustomerOrders that shows the CustomerName and the
OrderDate of all orders placed by customers.
 The view should combine data from both Customer and Order tables using the CustomerID.

4. Create a View to Find Top Earners

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a SQL query to create a view called TopEarners that displays the EmployeeID, FirstName,
LastName, and Salary of employees who have a salary greater than 50,000.
 The view should make it easy to query the top earners without writing a complex query every time.

5. Create a View for Product Sales Details

Problem Statement: The Product table contains ProductID, ProductName, and Price, and the Sales table
contains SaleID, ProductID, and SaleAmount.

Task:

 Write a SQL query to create a view called ProductSalesDetails that shows the ProductName and the
SaleAmount for each sale.
 The view should join the Product and Sales tables based on ProductID.
6. Create a View for Average Salary by Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, DepartmentID, and
Salary, and the Department table contains DepartmentID, DepartmentName.

Task:

 Write a SQL query to create a view called AverageSalaryByDepartment that shows the
DepartmentName and the average salary (AVG(Salary)) for each department.
 The view should group the data by DepartmentID and simplify the process of calculating the average
salary in any department.

7. Create a View to Display Product Prices Above 100

Problem Statement: The Product table contains ProductID, ProductName, and Price.

Task:

 Write a SQL query to create a view called ExpensiveProducts that displays ProductID, ProductName,
and Price for products whose price is greater than 100.
 The view should make it easier to query expensive products without rewriting the filtering conditions.

8. Create a View for Employee and Project Assignment

Problem Statement: The Employee table contains EmployeeID, EmployeeName, and ProjectID, and the
Project table contains ProjectID, ProjectName.

Task:

 Write a SQL query to create a view called EmployeeProjectAssignment that shows the EmployeeName
and the ProjectName they are assigned to.
 The view should simplify the retrieval of employee-project assignments by joining the Employee and
Project tables.

9. Create a View for Sales by Month

Problem Statement: The Sales table contains SaleID, ProductID, SaleAmount, and SaleDate.

Task:

 Write a SQL query to create a view called MonthlySales that shows the total SaleAmount for each
month (grouped by year and month).
 The view should calculate monthly sales totals by extracting the month and year from the SaleDate
column.
10. Create a View for Customer's Last Order

Problem Statement: The Customer table contains CustomerID, CustomerName, and the Order table contains
OrderID, CustomerID, and OrderDate.

Task:

 Write a SQL query to create a view called CustomerLastOrder that shows the CustomerName and the
OrderDate of their most recent order.
 The view should use the MAX() function to find the latest order for each customer.

11. Create a View for Employee Salary Above Average

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a SQL query to create a view called AboveAverageSalary that displays EmployeeID, FirstName,
LastName, and Salary for employees whose salary is greater than the average salary of all employees.
 Use the AVG() function to calculate the average salary for the comparison.

12. Create a View for Customers Who Ordered Multiple Products

Problem Statement: The Customer table contains CustomerID, CustomerName, and the Order table contains
OrderID, CustomerID, and ProductID.

Task:

 Write a SQL query to create a view called CustomersWithMultipleOrders that shows customers who
have ordered more than one product.
 The view should group the data by CustomerID and use the HAVING clause to filter customers with more
than one order.

13. Create a View to Show Product Stock Status

Problem Statement: The Product table contains ProductID, ProductName, StockQuantity, and Price.

Task:

 Write a SQL query to create a view called ProductStockStatus that shows ProductName,
StockQuantity, and Price for each product.
 The view should simplify queries about product availability.
14. Create a View for Total Revenue by Product

Problem Statement: The Product table contains ProductID, ProductName, and Price, and the Sales table
contains SaleID, ProductID, and SaleAmount.

Task:

 Write a SQL query to create a view called ProductRevenue that shows the total revenue (SaleAmount
* Price) generated by each product.
 The view should calculate total revenue by joining the Product and Sales tables.

15. Create a View for Top 5 Products by Sales

Problem Statement: The Product table contains ProductID, ProductName, and Price, and the Sales table
contains SaleID, ProductID, and SaleAmount.

Task:

 Write a SQL query to create a view called Top5ProductsBySales that displays the top 5 products by
total sales.
 Use the SUM() function to calculate total sales and order the results in descending order. The view
should only return the top 5 products based on total sales.

Managing Views:

16. Alter an Existing View to Add a New Column

Problem Statement: The EmployeeInfo view currently displays EmployeeID, FirstName, and LastName.

Task:

 Write a SQL query to alter the EmployeeInfo view to also include the DepartmentID.
 Ensure the view shows EmployeeID, FirstName, LastName, and DepartmentID.

17. Drop a View

Problem Statement: You no longer need the TopEarners view, which was previously created.

Task:
 Write a SQL query to drop the TopEarners view from the database.

PL/SQL programs using conditional statements:


1. Check if Employee Salary is Above a Threshold

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a PL/SQL block that checks if an employee’s salary is above 50,000.


 If the salary is above 50,000, display the message: "Salary is above threshold."
 If the salary is below or equal to 50,000, display the message: "Salary is below threshold."

2. Determine Student Grade

Problem Statement: The Student table contains StudentID, StudentName, and Marks.

Task:

 Write a PL/SQL block that assigns a grade based on the Marks (out of 100):
o If marks are greater than or equal to 90, assign grade 'A'.
o If marks are between 70 and 89 (inclusive), assign grade 'B'.
o If marks are between 50 and 69 (inclusive), assign grade 'C'.
o If marks are below 50, assign grade 'D'.
 Display the StudentName and the assigned grade.

3. Check if Product is in Stock

Problem Statement: The Product table contains ProductID, ProductName, and StockQuantity.

Task:

 Write a PL/SQL block that checks if the StockQuantity of a product is greater than zero.
 If the quantity is greater than zero, display the message: "Product is in stock."
 If the quantity is zero or less, display the message: "Product is out of stock."

4. Determine Discount Based on Customer Type

Problem Statement: The Customer table contains CustomerID, CustomerName, and CustomerType (where
customer types are 'Regular' or 'Premium').
Task:

 Write a PL/SQL block that determines the discount for a customer based on their CustomerType.
o If the CustomerType is 'Premium', give a 15% discount.
o If the CustomerType is 'Regular', give a 5% discount.
 Display the CustomerName and the discount percentage.

5. Check if Student Passed or Failed

Problem Statement: The Student table contains StudentID, StudentName, and Marks (out of 100).

Task:

 Write a PL/SQL block to check if a student has passed or failed.


o If the Marks are greater than or equal to 40, display the message: "Student Passed."
o If the Marks are less than 40, display the message: "Student Failed."

6. Grade Based on Age

Problem Statement: The Person table contains PersonID, Name, and Age.

Task:

 Write a PL/SQL block that assigns a category based on Age:


o If the Age is between 0 and 12, assign the category 'Child'.
o If the Age is between 13 and 19, assign the category 'Teenager'.
o If the Age is between 20 and 59, assign the category 'Adult'.
o If the Age is 60 or above, assign the category 'Senior'.
 Display the Name and the assigned category.

7. Determine Eligible for Voting

Problem Statement: The Citizen table contains CitizenID, Name, and Age.

Task:

 Write a PL/SQL block that checks if a person is eligible to vote.


o If the Age is 18 or above, display the message: "Eligible to Vote."
o If the Age is below 18, display the message: "Not Eligible to Vote."

8. Find the Maximum of Two Numbers


Problem Statement: There are two variables: Num1 and Num2.

Task:

 Write a PL/SQL block that compares the two numbers and displays the greater number.
o If Num1 is greater than Num2, display the message: "Num1 is greater."
o If Num2 is greater than Num1, display the message: "Num2 is greater."
o If both numbers are equal, display the message: "Both numbers are equal."

9. Calculate Employee Bonus

Problem Statement: The Employee table contains EmployeeID, EmployeeName, and Salary.

Task:

 Write a PL/SQL block that calculates the bonus for employees based on their salary:
o If the Salary is greater than 60,000, give a bonus of 10%.
o If the Salary is between 30,000 and 60,000, give a bonus of 5%.
o If the Salary is less than 30,000, give a bonus of 2%.
 Display the EmployeeName and the bonus amount.

10. Determine Number of Days in a Month

Problem Statement: There is a variable MonthNumber (1 for January, 2 for February, etc.) and Year (4-digit
year).

Task:

 Write a PL/SQL block to calculate the number of days in a given month for a particular year.
o Use conditional statements to determine if the month has 31, 30, or 28/29 days (for leap years).
 Display the MonthNumber, Year, and the number of days in that month.

11. Check Age Eligibility for a Scholarship

Problem Statement: The Student table contains StudentID, StudentName, Age, and Marks.

Task:

 Write a PL/SQL block that checks if a student is eligible for a scholarship based on the following
criteria:
o If the student’s Age is between 18 and 25 (inclusive) and Marks are greater than or equal to 75,
they are eligible for a scholarship.
 Display the StudentName and a message: "Eligible for Scholarship" or "Not Eligible for Scholarship".
12. Categorize Products by Price Range

Problem Statement: The Product table contains ProductID, ProductName, and Price.

Task:

 Write a PL/SQL block that categorizes products based on their price:


o If Price is less than 100, categorize as 'Budget'.
o If Price is between 100 and 500, categorize as 'Mid-range'.
o If Price is greater than 500, categorize as 'Premium'.
 Display the ProductName and its category.

13. Determine Discount for Sales Amount

Problem Statement: The Sales table contains SaleID, ProductID, and SaleAmount.

Task:

 Write a PL/SQL block that determines the discount based on SaleAmount:


o If SaleAmount is greater than 10,000, give a 10% discount.
o If SaleAmount is between 5,000 and 10,000, give a 5% discount.
o If SaleAmount is below 5,000, no discount.
 Display the SaleAmount and the discount percentage.

14. Find the Largest of Three Numbers

Problem Statement: There are three variables: Num1, Num2, and Num3.

Task:

 Write a PL/SQL block that finds the largest of the three numbers.
o If Num1 is the largest, display "Num1 is the largest".
o If Num2 is the largest, display "Num2 is the largest".
o If Num3 is the largest, display "Num3 is the largest".
o If there is a tie, display the appropriate message for the tied values.

15. Calculate Bonus Based on Years of Service

Problem Statement: The Employee table contains EmployeeID, EmployeeName, and YearsOfService.

Task:

 Write a PL/SQL block to calculate the bonus based on YearsOfService:


o If YearsOfService is greater than or equal to 5, the bonus is 20% of the salary.
o If YearsOfService is between 2 and 4 years, the bonus is 10%.
o If YearsOfService is less than 2, the bonus is 5%.
 Display the EmployeeName and the calculated bonus.

Here are some simple problem statements that focus on creating implicit and explicit cursors in PL/SQL for
diploma students. These problems are designed to help students understand and practice the concepts of cursors
in database programming.

1. Implicit Cursor: Retrieve All Employees' Names

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a PL/SQL block that retrieves all employee names (i.e., FirstName and LastName) from the
Employee table using an implicit cursor.
 Use a SELECT INTO statement to fetch the data and display it using DBMS_OUTPUT.PUT_LINE.

2. Implicit Cursor: Calculate Total Salary of Employees

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a PL/SQL block that calculates the total salary of all employees using an implicit cursor.
 Use the SUM() aggregate function to compute the total and display the result using
DBMS_OUTPUT.PUT_LINE.

3. Explicit Cursor: Retrieve Employee Details by Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, DepartmentID, and
Salary. The Department table contains DepartmentID and DepartmentName.

Task:

 Write a PL/SQL block that uses an explicit cursor to fetch and display the FirstName, LastName, and
DepartmentName of employees working in a particular department (e.g., DepartmentID = 10).
 Display each employee's information using DBMS_OUTPUT.PUT_LINE.
4. Explicit Cursor: Display Employees with Salary Above 50,000

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a PL/SQL block that uses an explicit cursor to fetch all employees whose salary is greater than
50,000.
 For each employee, display the FirstName, LastName, and Salary using DBMS_OUTPUT.PUT_LINE.

5. Implicit Cursor: Count the Number of Employees in Each Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and DepartmentID.
The Department table contains DepartmentID and DepartmentName.

Task:

 Write a PL/SQL block that uses an implicit cursor to count the number of employees in each
department.
 Use the COUNT() aggregate function and display the department name along with the employee count
using DBMS_OUTPUT.PUT_LINE.

6. Explicit Cursor: Retrieve and Update Employee Salary

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a PL/SQL block that uses an explicit cursor to fetch employees whose salary is less than 40,000.
 For each employee, update their salary to 10% higher than their current salary.

7. Explicit Cursor: Find Employees Who Have Worked More Than 5 Years

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and HireDate.

Task:

 Write a PL/SQL block that uses an explicit cursor to fetch the names of employees who have worked
for more than 5 years (i.e., their HireDate is more than 5 years ago).
 Display the FirstName and LastName of each employee using DBMS_OUTPUT.PUT_LINE.

8. Implicit Cursor: Fetch a Single Employee's Salary


Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a PL/SQL block that uses an implicit cursor to fetch the salary of a specific employee (e.g.,
EmployeeID = 101).
 Display the employee's name and salary using DBMS_OUTPUT.PUT_LINE.

9. Explicit Cursor: Fetch Product Information Based on Price Range

Problem Statement: The Product table contains ProductID, ProductName, and Price.

Task:

 Write a PL/SQL block that uses an explicit cursor to fetch all products whose price is between 50 and
200.
 Display the ProductName and Price of each product using DBMS_OUTPUT.PUT_LINE.

10. Explicit Cursor: Retrieve All Customers Who Ordered Products

Problem Statement: The Customer table contains CustomerID, CustomerName, and PhoneNumber. The Order
table contains OrderID, CustomerID, and OrderDate.

Task:

 Write a PL/SQL block that uses an explicit cursor to fetch and display the names of customers who
have placed an order.
 Join the Customer and Order tables to get the desired result, and display the CustomerName using
DBMS_OUTPUT.PUT_LINE.

11. Implicit Cursor: Calculate Average Salary of Employees

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.

Task:

 Write a PL/SQL block that calculates the average salary of all employees using an implicit cursor.
 Use the AVG() aggregate function and display the result using DBMS_OUTPUT.PUT_LINE.

12. Explicit Cursor: Retrieve All Products Sold in a Given Month

Problem Statement: The Sales table contains SaleID, ProductID, SaleAmount, and SaleDate. The Product
table contains ProductID, ProductName, and Price.
Task:

 Write a PL/SQL block that uses an explicit cursor to fetch all products sold in a given month (e.g.,
October).
 Display the ProductName and SaleAmount of each product using DBMS_OUTPUT.PUT_LINE.

13. Implicit Cursor: Fetch Employee Information for a Given Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, DepartmentID, and
Salary.

Task:

 Write a PL/SQL block that uses an implicit cursor to fetch the names of all employees from a specific
department (e.g., DepartmentID = 5).
 Display the FirstName and LastName of each employee using DBMS_OUTPUT.PUT_LINE.

14. Explicit Cursor: Display Product Information Based on Category

Problem Statement: The Product table contains ProductID, ProductName, CategoryID, and Price. The
Category table contains CategoryID and CategoryName.

Task:

 Write a PL/SQL block that uses an explicit cursor to display all products from a specific category (e.g.,
CategoryName = 'Electronics').
 Join the Product and Category tables to get the results, and display the ProductName and Price of
each product using DBMS_OUTPUT.PUT_LINE.

15. Implicit Cursor: Fetch Total Sales for a Given Year

Problem Statement: The Sales table contains SaleID, ProductID, SaleAmount, and SaleDate.

Task:

 Write a PL/SQL block that uses an implicit cursor to fetch the total sales (SaleAmount) for a specific
year (e.g., 2023).
 Use the SUM() aggregate function and display the total sales using DBMS_OUTPUT.PUT_LINE.

16. Explicit Cursor: Calculate Total Revenue from Sales


Problem Statement: The Sales table contains SaleID, ProductID, SaleAmount, and SaleDate. The Product
table contains ProductID, ProductName, and Price.

Task:

 Write a PL/SQL block that uses an explicit cursor to calculate the total revenue generated by all sales,
considering both the SaleAmount and Price of each product.
 Display the total revenue using DBMS_OUTPUT.PUT_LINE.

Exception Handling:

1. Handle Division by Zero (Pre-defined Exception)

Problem Statement: Write a PL/SQL block that performs a division of two numbers. If the second number is
zero, handle the ZERO_DIVIDE exception and display the message: "Cannot divide by zero."

Task:

 Declare two variables Num1 and Num2 and initialize them with values.
 Attempt to divide Num1 by Num2 and catch the ZERO_DIVIDE exception.
 Display the result or the exception message accordingly.

2. Handle Invalid Number Format (Pre-defined Exception)

Problem Statement: Write a PL/SQL block that attempts to convert a string to a number. If the string is not a
valid number, handle the VALUE_ERROR exception and display the message: "Invalid number format."

Task:

 Declare a variable to store a string (e.g., str_value) and try to convert it to a number.
 Catch the VALUE_ERROR exception if the conversion fails.
 Display an appropriate message when the exception occurs.

3. Handle No Data Found (Pre-defined Exception)

Problem Statement: Write a PL/SQL block that queries the Employee table to retrieve an employee's salary
based on their EmployeeID. If no data is found for the given EmployeeID, handle the NO_DATA_FOUND exception
and display the message: "Employee not found."

Task:

 Use a SELECT INTO query to fetch the Salary for an EmployeeID.


 If no employee is found for the given ID, handle the NO_DATA_FOUND exception and display the error
message.
4. Handle Too Many Rows (Pre-defined Exception)

Problem Statement: Write a PL/SQL block that queries the Employee table to fetch the EmployeeID and
Salary for a given DepartmentID. If the query returns more than one row, handle the TOO_MANY_ROWS
exception and display the message: "Query returned multiple rows."

Task:

 Write a SELECT INTO query to fetch employee details based on DepartmentID.


 If more than one row is returned, catch the TOO_MANY_ROWS exception and display the appropriate
message.

5. Handle Invalid Employee ID (User-defined Exception)

Problem Statement: Write a PL/SQL block that checks if an employee’s EmployeeID exists in the Employee
table. If the EmployeeID does not exist, raise a user-defined exception and display the message: "Invalid
Employee ID."

Task:

 Declare a user-defined exception, Invalid_Employee_Exception.


 Check if the EmployeeID exists in the Employee table.
 If not, raise the user-defined exception and display the error message.

6. Handle Salary Less Than Minimum (User-defined Exception)

Problem Statement: Write a PL/SQL block that checks if an employee’s salary is less than the minimum
required salary (e.g., 20,000). If the salary is below the minimum, raise a user-defined exception and display the
message: "Salary is below the minimum requirement."

Task:

 Declare a user-defined exception, Salary_Below_Minimum.


 Check if the Salary of an employee is less than the minimum salary (20,000).
 If the salary is too low, raise the exception and display the appropriate message.

7. Handle Inactive Account (User-defined Exception)

Problem Statement: Write a PL/SQL block that checks if a customer's account is active before processing a
transaction. If the account is inactive, raise a user-defined exception and display the message: "Account is
inactive."

Task:
 Declare a user-defined exception, Inactive_Account_Exception.
 Check the Status of the customer's account in the Customer table.
 If the Status is 'Inactive', raise the exception and display the message.

8. Handle Insufficient Funds (User-defined Exception)

Problem Statement: Write a PL/SQL block that checks if a customer's account has sufficient funds for a
transaction. If the Balance is less than the transaction amount, raise a user-defined exception and display the
message: "Insufficient funds."

Task:

 Declare a user-defined exception, Insufficient_Funds_Exception.


 Check if the Balance in the Account table is sufficient for a transaction.
 If the balance is insufficient, raise the exception and display the message.

9. Handle Unsuccessful Update (User-defined Exception)

Problem Statement: Write a PL/SQL block that attempts to update the salary of an employee. If the update
fails (for example, if the employee does not exist), raise a user-defined exception and display the message:
"Update failed."

Task:

 Declare a user-defined exception, Update_Failed_Exception.


 Attempt to update the Salary in the Employee table based on EmployeeID.
 If the update fails (e.g., employee not found), raise the exception and display the message.

10. Handle Transaction Error (User-defined Exception)

Problem Statement: Write a PL/SQL block that processes a transaction by deducting the amount from one
account and adding it to another. If there’s an error during the transaction (e.g., insufficient funds, invalid
account), raise a user-defined exception and display the message: "Transaction error."

Task:

 Declare a user-defined exception, Transaction_Error_Exception.


 Deduct the amount from one account and add it to another account.
 If any error occurs during the transaction, raise the exception and display the message.

11. Handle Product Price Error (User-defined Exception)


Problem Statement: Write a PL/SQL block that checks the price of a product before applying a discount. If the
price is negative or zero, raise a user-defined exception and display the message: "Invalid product price."

Task:

 Declare a user-defined exception, Invalid_Price_Exception.


 Check the price of the product in the Product table.
 If the price is invalid (negative or zero), raise the exception and display the message.

12. Handle Employee Age Validation (User-defined Exception)

Problem Statement: Write a PL/SQL block that validates an employee's age before inserting it into the
Employee table. If the age is less than 18 or greater than 60, raise a user-defined exception and display the
message: "Invalid age for employee."

Task:

 Declare a user-defined exception, Invalid_Age_Exception.


 Check if the employee’s age is within a valid range (18-60).
 If not, raise the exception and display the message.

13. Handle Unauthorized Access (User-defined Exception)

Problem Statement: Write a PL/SQL block that checks if a user is authorized to access a particular resource. If
the user does not have permission, raise a user-defined exception and display the message: "Unauthorized
access."

Task:

 Declare a user-defined exception, Unauthorized_Access_Exception.


 Check the user's role or permission in the User table.
 If the user does not have the required permissions, raise the exception and display the message.

14. Handle Duplicate Employee Record (User-defined Exception)

Problem Statement: Write a PL/SQL block that checks if an employee already exists in the Employee table
before inserting a new record. If the employee already exists (based on EmployeeID), raise a user-defined
exception and display the message: "Employee already exists."

Task:

 Declare a user-defined exception, Duplicate_Employee_Exception.


 Check if the EmployeeID exists in the Employee table before attempting to insert the new record.
 If the employee already exists, raise the exception and display the message.
15. Handle Invalid Order Status (User-defined Exception)

Problem Statement: Write a PL/SQL block that checks if an order has a valid status in the Order table. If the
status is invalid (not 'Pending', 'Shipped', or 'Delivered'), raise a user-defined exception and display the
message: "Invalid order status."

Task:

 Declare a user-defined exception, Invalid_Order_Status_Exception.


 Check if the order status is valid before processing.
 If the status is invalid, raise the exception and display the message.

Here are some simple problem statements for creating functions in PL/SQL based on given database tables.
These exercises will help diploma students practice creating reusable functions to perform specific tasks within
a database.

1. Function to Calculate Employee's Annual Salary

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, Salary.

Task:

 Create a function that calculates and returns the annual salary of an employee by multiplying their
monthly salary (Salary column) by 12.
 The function should take EmployeeID as input and return the calculated annual salary.

2. Function to Get Total Number of Employees in a Department

Problem Statement: The Employee table contains EmployeeID, DepartmentID, FirstName, LastName.

Task:

 Create a function that takes DepartmentID as an input and returns the total number of employees in that
department.
 The function should return the count of employees from the Employee table based on the
DepartmentID.

3. Function to Check if a Product Exists in Stock


Problem Statement: The Product table contains ProductID, ProductName, StockQuantity.

Task:

 Create a function that takes ProductID as input and returns TRUE if the product exists in stock (i.e., the
StockQuantity is greater than 0), or FALSE if the product is out of stock.

4. Function to Calculate the Average Salary in a Department

Problem Statement: The Employee table contains EmployeeID, DepartmentID, Salary.

Task:

 Create a function that takes DepartmentID as input and returns the average salary of employees in that
department.
 The function should compute the average salary using the Salary column based on the DepartmentID.

5. Function to Get the Highest Salary in a Department

Problem Statement: The Employee table contains EmployeeID, DepartmentID, Salary.

Task:

 Create a function that takes DepartmentID as input and returns the highest salary among employees in
that department.
 The function should return the maximum salary based on the Salary column and DepartmentID.

6. Function to Retrieve Employee's Full Name

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName.

Task:

 Create a function that takes EmployeeID as input and returns the full name of the employee
(concatenation of FirstName and LastName).
 The function should return a string of the full name.

7. Function to Find the Total Sales Amount

Problem Statement: The Sales table contains SaleID, ProductID, SaleAmount.

Task:
 Create a function that takes ProductID as input and returns the total sales amount for that product.
 The function should sum the SaleAmount column for the given ProductID and return the total.

8. Function to Retrieve Employee's Department Name

Problem Statement: The Employee table contains EmployeeID, DepartmentID. The Department table
contains DepartmentID, DepartmentName.

Task:

 Create a function that takes EmployeeID as input and returns the DepartmentName of the employee by
joining the Employee and Department tables.
 The function should return the department name based on the DepartmentID.

9. Function to Get Discounted Price of a Product

Problem Statement: The Product table contains ProductID, ProductName, Price, DiscountPercentage.

Task:

 Create a function that takes ProductID as input and returns the discounted price of the product.
 The function should calculate the discounted price by applying the DiscountPercentage on the Price.

10. Function to Calculate Total Order Value

Problem Statement: The OrderDetails table contains OrderID, ProductID, Quantity, UnitPrice.

Task:

 Create a function that takes OrderID as input and returns the total value of the order (sum of Quantity *
UnitPrice for each product in that order).
 The function should calculate the total value by multiplying Quantity with UnitPrice for each product
in the order.

11. Function to Check if an Employee is Eligible for Bonus

Problem Statement: The Employee table contains EmployeeID, Salary, YearsOfService.

Task:

 Create a function that takes EmployeeID as input and checks if the employee is eligible for a bonus.
 The function should return TRUE if the employee's YearsOfService is greater than or equal to 5 years,
and FALSE otherwise.

12. Function to Get the Number of Days Between Two Dates

Problem Statement: The Employee table contains EmployeeID, HireDate, and TerminationDate.

Task:

 Create a function that takes EmployeeID as input and returns the number of days the employee worked
(difference between HireDate and TerminationDate).
 The function should calculate the difference and return the result in days.

13. Function to Get Employee's Age

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, BirthDate.

Task:

 Create a function that takes EmployeeID as input and calculates the employee's age based on their
BirthDate.
 The function should return the employee's age by comparing the BirthDate with the current date.

14. Function to Get the Number of Products in a Category

Problem Statement: The Product table contains ProductID, ProductName, CategoryID. The Category table
contains CategoryID, CategoryName.

Task:

 Create a function that takes CategoryID as input and returns the number of products in that category.
 The function should count the number of products in the Product table with the specified CategoryID.

15. Function to Get the Average Product Rating

Problem Statement: The ProductReview table contains ProductID, Rating.

Task:

 Create a function that takes ProductID as input and returns the average rating for that product.
 The function should calculate the average of all Rating values for the given ProductID in the
ProductReview table.
16. Function to Get the Maximum Discount Applied

Problem Statement: The Product table contains ProductID, ProductName, DiscountPercentage.

Task:

 Create a function that returns the maximum discount applied to any product.
 The function should find the highest value of DiscountPercentage across all products.

17. Function to Get Employee’s Supervisor

Problem Statement: The Employee table contains EmployeeID, ManagerID (which refers to another
EmployeeID).

Task:

 Create a function that takes an EmployeeID as input and returns the FirstName and LastName of the
employee's manager.
 The function should join the Employee table with itself to get the manager's details.

18. Function to Retrieve Last Order Date for a Customer

Problem Statement: The Order table contains OrderID, CustomerID, OrderDate.

Task:

 Create a function that takes CustomerID as input and returns the date of the last order placed by the
customer.
 The function should fetch the most recent OrderDate for the given CustomerID.

19. Function to Calculate the Average Sales for a Product

Problem Statement: The Sales table contains ProductID, SaleAmount, SaleDate.

Task:

 Create a function that takes ProductID as input and calculates the average sales amount for that product.
 The function should compute the average value of SaleAmount for the given ProductID.

20. Function to Retrieve the Most Expensive Product


Problem Statement: The Product table contains ProductID, ProductName, Price.

Task:

 Create a function that returns the name and price of the most expensive product in the Product table.
 The function should return the ProductName and Price of the product with the highest Price.

Triggers:

1. Trigger to Automatically Update Employee Salary

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, Salary, and
DepartmentID.

Task:

 Create a BEFORE INSERT trigger that automatically increases the salary of a new employee by 10%
if their Salary is less than 30,000.
 The trigger should fire before an employee is inserted into the Employee table, checking the Salary and
updating it accordingly.

2. Trigger to Log Changes in Employee Salary

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, Salary. The
SalaryLog table contains LogID, EmployeeID, OldSalary, NewSalary, ChangeDate.

Task:

 Create an AFTER UPDATE trigger that records the old and new salary of an employee when their
Salary is updated.
 The trigger should insert a record into the SalaryLog table with the EmployeeID, the old and new salary
values, and the date of the change.

3. Trigger to Prevent Deleting Employees with Active Projects

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Status. The
Project table contains ProjectID, EmployeeID, ProjectName, and Status.

Task:

 Create a BEFORE DELETE trigger that prevents an employee from being deleted if they are currently
assigned to an active project (i.e., Project.Status = 'Active').
 If the employee is assigned to an active project, raise an exception preventing the delete operation.
4. Trigger to Automatically Set Account Status

Problem Statement: The Customer table contains CustomerID, CustomerName, and Status. The Account
table contains AccountID, CustomerID, and Balance.

Task:

 Create a BEFORE INSERT trigger that sets the Status of a customer to 'Inactive' if their Balance
is less than 100, otherwise set it to 'Active'.
 The trigger should automatically set the Status in the Customer table based on the Balance of the
customer's account.

5. Trigger to Maintain Stock Quantity

Problem Statement: The Product table contains ProductID, ProductName, and StockQuantity. The
OrderDetails table contains OrderID, ProductID, Quantity.

Task:

 Create an AFTER INSERT trigger that automatically updates the StockQuantity in the Product table
when a new order is placed in the OrderDetails table.
 The trigger should reduce the StockQuantity of the product by the Quantity ordered.

6. Trigger to Prevent Negative Account Balance

Problem Statement: The Account table contains AccountID, CustomerID, and Balance.

Task:

 Create a BEFORE UPDATE trigger that prevents the Balance from being updated to a negative value.
 If an update attempts to set the Balance to a negative value, the trigger should raise an exception and
prevent the update.

7. Trigger to Set Default Order Status

Problem Statement: The Order table contains OrderID, CustomerID, OrderDate, and OrderStatus.

Task:

 Create a BEFORE INSERT trigger that automatically sets the OrderStatus to 'Pending' if no value
is provided during the insertion of a new order.
 If OrderStatus is provided, the trigger should leave it unchanged.
8. Trigger to Track Deletions of Products

Problem Statement: The Product table contains ProductID, ProductName, Price. The DeletedProductLog
table contains LogID, ProductID, ProductName, Price, and DeleteDate.

Task:

 Create an AFTER DELETE trigger that inserts information about the deleted product (including
ProductID, ProductName, and Price) into the DeletedProductLog table whenever a product is deleted
from the Product table.

9. Trigger to Prevent Negative Quantity in Inventory

Problem Statement: The Inventory table contains ProductID, ProductName, and Quantity.

Task:

 Create an AFTER UPDATE trigger that prevents the Quantity of a product in the Inventory table
from being reduced below zero.
 If the updated quantity is less than zero, the trigger should raise an error and prevent the update.

10. Trigger to Send Notification After Order Placement

Problem Statement: The Order table contains OrderID, CustomerID, OrderDate, and TotalAmount. The
Notification table contains NotificationID, CustomerID, Message, and SentDate.

Task:

 Create an AFTER INSERT trigger that sends a notification to the customer when a new order is placed.
 The notification should be inserted into the Notification table, with a message like "Your order has
been placed successfully" and the current date as the SentDate.

11. Trigger to Update Inventory When a Product is Returned

Problem Statement: The SalesOrder table contains OrderID, ProductID, Quantity. The Product table
contains ProductID, ProductName, and StockQuantity.

Task:

 Create an AFTER UPDATE trigger that updates the StockQuantity in the Product table when a
product is returned (e.g., when Quantity is negative).
 The trigger should increase the StockQuantity in the Product table based on the returned Quantity.
12. Trigger to Prevent Order Deletion if Payment is Made

Problem Statement: The Order table contains OrderID, OrderDate, OrderStatus. The Payment table
contains PaymentID, OrderID, AmountPaid, and PaymentDate.

Task:

 Create an AFTER DELETE trigger that prevents the deletion of an order if a payment has already been
made for that order.
 If a payment exists for the OrderID, the trigger should raise an error and prevent the deletion.

13. Trigger to Log Changes in Customer Status

Problem Statement: The Customer table contains CustomerID, CustomerName, and Status. The
CustomerStatusLog table contains LogID, CustomerID, OldStatus, NewStatus, and ChangeDate.

Task:

 Create an AFTER UPDATE trigger that logs any changes in the Status of a customer in the
CustomerStatusLog table.
 The log should contain the CustomerID, the old and new status, and the date of the change.

14. Trigger to Automatically Assign Employee to a Department

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and DepartmentID.
The Department table contains DepartmentID, DepartmentName.

Task:

 Create a BEFORE INSERT trigger that automatically assigns an employee to the default department
(e.g., DepartmentID = 1) if no department is specified during insertion.
 If a DepartmentID is provided, the trigger should leave it unchanged.

15. Trigger to Automatically Update Order Status to 'Shipped'

Problem Statement: The Order table contains OrderID, OrderStatus, OrderDate, and ShippingDate.

Task:

 Create an AFTER INSERT trigger that automatically sets the OrderStatus to 'Shipped' when the
ShippingDate is not null.
 The trigger should update the OrderStatus to 'Shipped' if a ShippingDate is provided during the
order insertion.

16. Trigger to Prevent Inserting Duplicate Records

Problem Statement: The Product table contains ProductID, ProductName, and Price.

Task:

 Create a BEFORE INSERT trigger that checks if a product with the same ProductName already exists
in the Product table.
 If the product exists, the trigger should raise an exception and prevent the insertion.

17. Trigger to Track Employee Deletions

Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, DepartmentID.

Task:

 Create an AFTER DELETE trigger that inserts the details of a deleted employee into an
EmployeeAudit table, which contains AuditID, EmployeeID, FirstName, LastName, and DeletedDate.

You might also like