A method for any SQL question
Most SQL interview questions are a sentence and a few tables: “Find the employees who earn more than their manager.” Jumping straight into SELECT is how people end up with a query that almost works. A short routine avoids that:
- Read the tables. What is one row of each? Which columns are keys, and which can be NULL?
- Say the grain of the answer: “one row per employee”, “one row per department and month”. It tells you what to group by and what to join.
- Ask about the edge cases before the interviewer does: What if two people have the same salary? What if a department has no employees? What should come back when there’s no answer, no rows or NULL?
- Build it in steps. Write each step as a CTE with a name (
WITH ranked AS (…)), check it, then use it in the next one. - Test it on a tiny example in your head: three or four rows, including a tie and a NULL.
Here’s the routine on a classic: employees who earn more than their manager. One row is an employee, and manager_id points to another row of the same table. The answer is one row per employee. To compare an employee with their manager, put the table next to itself, a self-join:
SELECT e.name, 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;The edge case: the CEO has no manager (manager_id is NULL). The inner join drops them, which is right here, because they can’t earn more than a manager they don’t have.
The other classic is the second highest salary. With salaries 100, 100 and 90, the answer is 90: the question is about different salary amounts, so duplicates have to go first. And when there’s only one salary, the expected answer is usually a single row with NULL, not an empty result.
- Grain first: say “one row per X” out loud; most wrong answers come from joins that change the grain (fan-out before
sum) or groups at the wrong level. - Clarify ties and empties before coding:
row_numbervsrankvsdense_rank; “no rows” vs a NULL row; include or exclude zero-activity entities (left join from the full list). - Build with CTEs, one idea per step, then mention you could inline them. In PostgreSQL 12+ CTEs are inlined unless referenced twice or
MATERIALIZED, so readability costs nothing. - Classic traps to check aloud:
NOT INwith a NULL in the subquery,count(*)after a left join, integer division, conditions on the outer table inWHERE,BETWEENon timestamps, time zones when grouping by day. - Dialect:
LIMIT/OFFSET(PostgreSQL, MySQL, SQLite),FETCH FIRST n ROWS ONLY(standard, PostgreSQL, Oracle 12c+),TOPandOFFSET … FETCH(SQL Server); date functions differ everywhere. Say which dialect you’re writing. - Nth highest generalises:
dense_rank() = n, orDISTINCT … ORDER BY … OFFSET n - 1 LIMIT 1wrapped in a scalar subquery so an empty answer becomes NULL.
Predict the output
Salaries are 100, 100 and 90. What does this query return as the second highest salary?
SELECT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;Sorted descending, the rows are 100, 100, 90. OFFSET 1 skips one row and returns the second, which is the other 100. The question is about different amounts, so remove duplicates first: SELECT DISTINCT salary … OFFSET 1. And with a single employee this version returns no rows at all; wrapping it in a scalar subquery, SELECT (SELECT …) AS second_highest, turns that into one row with NULL.
-- 1. the biggest salary below the biggest (NULL when there is none)
SELECT max(salary) AS second_highest
FROM employees
WHERE salary < (SELECT max(salary) FROM employees);
-- 2. distinct amounts, skip one; the outer SELECT turns "no row" into NULL
SELECT (
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1
) AS second_highest;
-- 3. dense_rank: ties share a rank and no rank is skipped, so this works for any N
WITH ranked AS (
SELECT salary, dense_rank() OVER (ORDER BY salary DESC) AS rnk
FROM employees
)
SELECT max(salary) AS second_highest -- max() returns one row, NULL if empty
FROM ranked
WHERE rnk = 2;Practice: three warm-ups
Managers, departments and lonely customers
- List managers who have at least three direct reports, with how many they have.
- List every department with its number of employees, including departments with none (shown as 0).
- List customers (from the shop tables) who have never placed an order.
›
1 is a self-join or a plain GROUP BY manager_id, plus HAVING. 2 needs every department even without matches: which join keeps all rows of one side?
›
For 2, count a column of the employee side, not *: a department with no employees still gets one row from the left join. For 3, look for customers for whom no order exists.
SolutionTry it yourself first
-- 1
SELECT m.id, m.name, count(*) AS reports
FROM employees e
JOIN employees m ON m.id = e.manager_id
GROUP BY m.id, m.name
HAVING count(*) >= 3;
-- 2
SELECT d.name, count(e.id) AS employees
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id
GROUP BY d.id, d.name
ORDER BY employees DESC;
-- 3
SELECT c.id, c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);In 2, count(*) would show 1 for an empty department, because the left join keeps it as one row with NULLs. In 3, NOT IN (SELECT customer_id FROM orders) works only while customer_id can never be NULL; NOT EXISTS is safe either way.
Deep diveWhat interviewers actually gradeInterview favorite
A live SQL round usually scores four things, in this order.
- Correctness on the edge cases: ties, NULLs, duplicates, empty groups, the right answer when nothing matches. Interviewers often have a hidden test table with exactly those rows. Asking “should ties both count?” earns as much as solving it.
- The grain: does the result have one row per thing the question asked for? A join to
order_itemsbeforesum(o.total)multiplies totals; aGROUP BYwith an extra column splits groups. - Readability: named CTEs, aliases that mean something, one idea per step. A correct 40-line query nobody can follow scores lower than a clear one with a small bug you catch yourself.
- Performance, when asked: which index serves the query (
(department_id, salary DESC)for top earners per department), whyWHERE date(login_at) = …can’t use an index onlogin_atbut a range can, and that window functions sort, so aPARTITION BYon 100 million rows needs memory or an index in the same order.
Talk while you write: “First I’ll get one row per user and day, then number them.” If you’re stuck, write the brute-force version (a correlated subquery per row) and say how you’d improve it. That’s a far better signal than silence.
- State the grain, clarify ties, NULLs and empty results, build in CTEs, test on a tiny table with a tie and a NULL.
- Self-join for row-vs-related-row (employee vs manager). Left join from the full list plus
count(child.id)for zero counts.NOT EXISTSoverNOT IN. - Nth highest:
dense_rank() = norDISTINCT … OFFSET n - 1in a scalar subquery for NULL on empty. - Graded on edge cases, grain, readability, then indexes.
SELECT (SELECT DISTINCT salary FROM employees
ORDER BY salary DESC LIMIT 1 OFFSET 1) AS second_highest;
SELECT e.name FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;Check this part
How do you compare each employee with their manager when both are in the employees table?
Departments with their employee count, including empty ones. Which count is right after LEFT JOIN employees e?
Salaries 100, 100, 90. Which gives 90 as the second highest?
Only one employee exists. How do you return a row with NULL instead of no rows?