Advanced Database Lab Questions (PostgreSQL Compatible)
1. SQL Practice Questions
Q1. Create a relational schema for the following entities:
- Employee (EmpID, Name, Department, Salary)
- Department (DeptID, DeptName)
Write the SQL queries for the following:
a) Find the highest-paid employee in each department.
b) List all employees who work in the "Research" department.
c) Increase the salary of employees in the "HR" department by 10%.
d) List employees who earn more than the average salary.
Q2. Write SQL queries for the following:
a) Create a view that shows employees and their department names.
b) Write a query to delete employees who have not worked (assume workHours = 0 or an extended table).
c) Create an index on the Salary column to optimize performance.
d) Count the number of employees in each department.
e) Display departments with more than 5 employees.
2. Object and Object-Relational Database (PostgreSQL)
Q3. PostgreSQL supports user-defined types.
a) Create a user-defined type address_type with street, city, zipcode.
b) Use this type in a Customer table with the fields: (CustomerID, Name, Address address_type).
c) Insert a sample customer into this table.
d) Write a query to display the city of each customer.
Q4. Demonstrate inheritance in PostgreSQL.
a) Create a table Vehicle (VehicleID, Make, Model).
b) Create a table Car that inherits from Vehicle and has an extra column NumDoors.
c) Insert sample data in both tables.
d) Query all vehicles and show how inheritance works.
Advanced Database Lab Questions (PostgreSQL Compatible)
3. Triggers (PostgreSQL)
Q6. Write a trigger that automatically updates the LastUpdated timestamp of a Product table when any row is updated.
a) Create the Product table with fields: (ProductID, Name, Price, LastUpdated).
b) Write a BEFORE UPDATE trigger that sets LastUpdated = CURRENT_TIMESTAMP.
c) Update a row and show that the timestamp is updated.
4. Procedural Language (PL/pgSQL)
Q10. Create and Use PL/pgSQL Functions
a) Write a PL/pgSQL function get_employee_salary(emp_id INT) that returns the salary of the employee with the given
ID.
b) Modify the function to raise a notice if the salary is above 100000.
c) Test the function using a sample Employee table.
Q11. Function with Looping and Logic
Write a PL/pgSQL function factorial(n INTEGER) that calculates and returns the factorial of a number using a loop.
Q12. Function with IF-ELSE Conditions
Create a function evaluate_performance(score INT) that returns:
- 'Excellent' if score > 85
- 'Good' if score is between 70 and 85
- 'Needs Improvement' otherwise
Bonus / Integration Question
Q9. Combine object-relational features with triggers:
- Create a Student table using a composite type for contact_info (email TEXT, phone TEXT).
- Create a trigger that checks if email is NULL on insert and raises an exception.