Detailed SQL Sample Questions and Solutions
Q1: Find the second highest salary from an Employee table.
To get the second highest salary, you can use a subquery to find the max salary less than the highest:
SELECT MAX(salary) FROM Employee WHERE salary < (SELECT MAX(salary) FROM Employee);
Q2: Retrieve all employees who do not have a manager.
Rows with NULL in 'manager_id' usually indicate top-level employees:
SELECT * FROM Employee WHERE manager_id IS NULL;
Q3: Count the number of employees in each department.
GROUP BY clause helps to aggregate data based on department_id:
SELECT department_id, COUNT(*) AS total_employees FROM Employee GROUP BY department_id;
Q4: Get employees who joined in the last 3 months.
Assuming 'join_date' is of DATE type:
SELECT * FROM Employee WHERE join_date >= CURRENT_DATE - INTERVAL '3 months';
Q5: List departments having more than 5 employees.
Use HAVING to filter groups based on aggregate functions:
SELECT department_id FROM Employee GROUP BY department_id HAVING COUNT(*) > 5;
Q6: Retrieve employees with the highest salary in each department.
Use a correlated subquery or window function:
Using window function:
SELECT * FROM (
SELECT *, RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) as rank
FROM Employee
) ranked WHERE rank = 1;
Q7: Get the average salary per department and order them by average salary descending.
Use GROUP BY and ORDER BY together:
SELECT department_id, AVG(salary) AS avg_salary FROM Employee
GROUP BY department_id ORDER BY avg_salary DESC;