Key takeaways
- These are the SQL queries interviewers ask most often, from "second highest salary" to "top 3 per department" and "consecutive login days".
- Learn the patterns — self-join, GROUP BY + HAVING, window functions, anti-join — and you can solve new variations on the spot.
- Every query uses one sample schema:
employees(id, name, salary, dept_id, manager_id, hire_date)anddepartments(id, name).
Most SQL interviews include a live query round. The good news: the same 25 query patterns come up again and again. Each one below has a working solution in standard SQL (tested on PostgreSQL and MySQL 8). For theory questions — joins, normalization, indexes, ACID — see the top 100+ SQL interview questions.
Sample schema: employees(id, name, salary, dept_id, manager_id, hire_date) and departments(id, name).
Ranking and Nth value
1. Find the second highest salary
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);2. Find the Nth highest salary (here N = 3)
SELECT DISTINCT salary
FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees) t
WHERE rnk = 3;Use DENSE_RANK so that tied salaries don't skip a rank.
3. Top 3 earners in each department
SELECT dept_id, name, salary
FROM (
SELECT e.*, DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
FROM employees e
) t
WHERE rnk <= 3
ORDER BY dept_id, salary DESC;4. Highest-paid employee in each department (with the department name)
SELECT d.name AS department, e.name, e.salary
FROM employees e
JOIN departments d ON d.id = e.dept_id
WHERE e.salary = (SELECT MAX(salary) FROM employees x WHERE x.dept_id = e.dept_id);Duplicates
5. Find duplicate names
SELECT name, COUNT(*) AS cnt
FROM employees
GROUP BY name
HAVING COUNT(*) > 1;6. Delete duplicates, keeping the row with the lowest id
-- PostgreSQL
DELETE FROM employees e
USING employees d
WHERE e.name = d.name AND e.id > d.id;
-- MySQL 8 / portable
DELETE FROM employees
WHERE id IN (
SELECT id FROM (
SELECT id, ROW_NUMBER() OVER (PARTITION BY name ORDER BY id) AS rn FROM employees
) t WHERE rn > 1
);Joins and self-joins
7. Employees who earn more than their manager
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;8. Departments with no employees (anti-join)
SELECT d.name
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.id
WHERE e.id IS NULL;
-- or: WHERE NOT EXISTS (SELECT 1 FROM employees e WHERE e.dept_id = d.id)9. Employees with their manager's name (including those without a manager)
SELECT e.name, COALESCE(m.name, '— none —') AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;10. Count employees in each department, including empty departments
SELECT d.name, COUNT(e.id) AS headcount -- COUNT(e.id) counts 0 for no match
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.id
GROUP BY d.name
ORDER BY headcount DESC;Aggregation
11. Departments whose average salary is above the company average
SELECT dept_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY dept_id
HAVING AVG(salary) > (SELECT AVG(salary) FROM employees);12. Employees earning more than their department's average
SELECT name, dept_id, salary
FROM (SELECT e.*, AVG(salary) OVER (PARTITION BY dept_id) AS dept_avg FROM employees e) t
WHERE salary > dept_avg;13. Number of employees hired each year
SELECT EXTRACT(YEAR FROM hire_date) AS yr, COUNT(*) AS hires
FROM employees
GROUP BY EXTRACT(YEAR FROM hire_date)
ORDER BY yr;14. Each employee's percentage of their department's total salary
SELECT name, dept_id, salary,
ROUND(100.0 * salary / SUM(salary) OVER (PARTITION BY dept_id), 2) AS pct_of_dept
FROM employees;Running totals and time series
For these, assume orders(id, customer_id, amount, order_date) and logins(user_id, login_date).
15. Running total of sales by date
SELECT order_date, SUM(amount) AS day_total,
SUM(SUM(amount)) OVER (ORDER BY order_date) AS running_total
FROM orders
GROUP BY order_date
ORDER BY order_date;16. Month-over-month revenue change
WITH m AS (
SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS revenue -- MySQL: DATE_FORMAT(order_date, '%Y-%m-01')
FROM orders GROUP BY 1
)
SELECT month, revenue,
revenue - LAG(revenue) OVER (ORDER BY month) AS change,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month)) / LAG(revenue) OVER (ORDER BY month), 1) AS pct
FROM m ORDER BY month;17. 7-day moving average
SELECT order_date, daily,
AVG(daily) OVER (ORDER BY order_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7
FROM (SELECT order_date, SUM(amount) AS daily FROM orders GROUP BY order_date) d;18. Users who logged in on 3 or more consecutive days (gaps and islands)
WITH d AS (
SELECT DISTINCT user_id, login_date FROM logins
), g AS (
SELECT user_id, login_date,
login_date - CAST(ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) AS INT) AS grp
FROM d
)
SELECT user_id, MIN(login_date) AS streak_start, COUNT(*) AS days
FROM g
GROUP BY user_id, grp
HAVING COUNT(*) >= 3;The trick: within a run of consecutive dates, date minus row number is constant. (In MySQL, use DATE_SUB(login_date, INTERVAL rn DAY).)
19. Each customer's first order
SELECT customer_id, id AS first_order_id, order_date
FROM (SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, id) AS rn FROM orders o) t
WHERE rn = 1;20. Customers who ordered in January but not in February
SELECT DISTINCT customer_id FROM orders
WHERE order_date >= '2026-01-01' AND order_date < '2026-02-01'
AND customer_id NOT IN (
SELECT customer_id FROM orders
WHERE order_date >= '2026-02-01' AND order_date < '2026-03-01'
AND customer_id IS NOT NULL
);Reshaping and miscellaneous
21. Pivot: total salary per department per hire year
SELECT dept_id,
SUM(CASE WHEN EXTRACT(YEAR FROM hire_date) = 2024 THEN salary ELSE 0 END) AS y2024,
SUM(CASE WHEN EXTRACT(YEAR FROM hire_date) = 2025 THEN salary ELSE 0 END) AS y2025,
SUM(CASE WHEN EXTRACT(YEAR FROM hire_date) = 2026 THEN salary ELSE 0 END) AS y2026
FROM employees
GROUP BY dept_id;22. Find missing ids in a sequence
SELECT id + 1 AS missing_from, next_id - 1 AS missing_to
FROM (SELECT id, LEAD(id) OVER (ORDER BY id) AS next_id FROM employees) t
WHERE next_id - id > 1;23. Print an employee hierarchy with a recursive CTE
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 1 AS level FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, c.level + 1
FROM employees e JOIN chain c ON e.manager_id = c.id
)
SELECT LPAD('', (level - 1) * 2, ' ') || name AS org_chart, level -- MySQL: CONCAT(REPEAT(' ', (level-1)*2), name)
FROM chain ORDER BY level, name;24. Median salary
-- PostgreSQL
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median FROM employees;
-- Portable (MySQL 8)
SELECT AVG(salary) AS median FROM (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary) AS rn, COUNT(*) OVER () AS cnt FROM employees
) t
WHERE rn IN (FLOOR((cnt + 1) / 2.0), CEIL((cnt + 1) / 2.0));25. Swap the values of a column (male ↔ female) in one UPDATE
UPDATE employees
SET gender = CASE gender WHEN 'M' THEN 'F' WHEN 'F' THEN 'M' ELSE gender END;How to practise
Type every query yourself on a real database (a free PostgreSQL or MySQL instance is enough). Say the pattern out loud before writing — "this is top-N per group, so ROW_NUMBER with PARTITION BY" — because interviewers grade your reasoning as much as the result. Then revise the theory in the SQL interview questions guide and test yourself with the SQL quiz.