DMS - Practice Program List
DMS - Practice Program List
Problem Statement: Create a database for managing student information at a school. The database should
contain the following tables:
Tasks:
Problem Statement: Create a database for a library to manage books and borrowers. The database should
contain the following tables:
Tasks:
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:
Problem Statement: Create a database to manage the inventory of a store. The database should contain the
following tables:
Tasks:
Problem Statement: Create a database for an online shopping platform. The database should include the
following tables:
Tasks:
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:
7. Sales Database
Problem Statement: Create a database to store sales transactions. The database should have the following
tables:
Tasks:
Problem Statement: Create a database to store student grades for various subjects. The database should contain
the following tables:
Tasks:
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:
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:
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:
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:
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.
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
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:
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.
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:
Tasks:
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:
Tasks:
Problem Statement: The Employee table contains the following columns: EmployeeID, FirstName, LastName,
Salary, BonusPercent.
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.
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.
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.
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.
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.
Problem Statement: The Student table contains StudentID, FirstName, LastName, DateOfBirth.
Task:
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.
Task:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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'
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.
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".
Task:
Write a SQL query to find all orders with a TotalAmount greater than 1000.
Use the > relational operator.
Display OrderID and TotalAmount.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Department.
Task:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.
Task:
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
Problem Statement: The Employee table contains EmployeeID, FirstName, LastName, and Salary.
Task:
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.
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."
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.
Problem Statement: The Student table contains StudentID, StudentName, and Marks (out of 100).
Task:
Problem Statement: The Person table contains PersonID, Name, and Age.
Task:
Problem Statement: The Citizen table contains CitizenID, Name, and Age.
Task:
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."
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.
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.
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:
Problem Statement: The Sales table contains SaleID, ProductID, and SaleAmount.
Task:
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.
Problem Statement: The Employee table contains EmployeeID, EmployeeName, and YearsOfService.
Task:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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:
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:
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:
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:
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.
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:
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:
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:
Task:
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:
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:
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:
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.