Top 15 SQL Interview
Questions
(Big 4 Companies)
- Ananya Laha
Here are the Top 15 SQL Interview Questions (Big 4 Edition) with sample
answers- formatted clearly so you can save and revise:
1. Find the second highest salary from an Employee table.
SELECT MAX(salary) AS SecondHighest
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee);
2. Retrieve duplicate records from a table.
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > 1;
3. Fetch the Nth highest salary from a table.
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET n-1;
4. Find employees who joined in the last 3 months.
SELECT *
FROM Employee
WHERE join_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH);
5. Display all departments along with the number of employees in each.
SELECT department, COUNT(*) AS employee_count
FROM Employee
GROUP BY department;
6. Find employees who never submitted timesheets.
SELECT *
FROM Employees
WHERE emp_id NOT IN (SELECT emp_id FROM Timesheets);
7. Get the department with the highest average salary.
SELECT department
FROM Employee
GROUP BY department
ORDER BY AVG(salary) DESC
LIMIT 1;
8. List top 3 highest paid employees in each department.
SELECT *
FROM (
SELECT *, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS
rnk
FROM Employee
) AS ranked
WHERE rnk <= 3;
9. Employees with salaries higher than their department’s average.
SELECT *
FROM Employee e
WHERE salary > (
SELECT AVG(salary)
FROM Employee
WHERE department = e.department
);
10. Pivot rows into columns using CASE.
SELECT id,
MAX(CASE WHEN month = 'Jan' THEN sales END) AS JanSales,
MAX(CASE WHEN month = 'Feb' THEN sales END) AS FebSales
FROM Sales
GROUP BY id;
11. Cumulative salary of employees by department (running total).
SELECT name, department, salary,
SUM(salary) OVER (PARTITION BY department ORDER BY name) AS
cumulative_salary
FROM Employee;
12. Identify missing IDs in a sequence.
SELECT t1.id + 1 AS missing_id
FROM table_name t1
WHERE NOT EXISTS (
SELECT 1
FROM table_name t2
WHERE t2.id = t1.id + 1
);
13. Swap two column values without using temp variable.
UPDATE Employee
SET col1 = col2,
col2 = col1;
14. Display employees who have the same salary.
SELECT *
FROM Employee e1
WHERE EXISTS (
SELECT 1
FROM Employee e2
WHERE e1.salary = e2.salary AND e1.id != e2.id
);
15. Get the latest record for each employee from audit table.
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY emp_id ORDER BY
updated_at DESC) AS rn
FROM audit_log
) AS temp
WHERE rn = 1;