Joining and aggregating · core
Classic interview queries
A handful of query patterns come up again and again in live SQL rounds: Nth highest value, duplicates, rows with no match, top N per group, latest row per group and running totals, and each has a clean standard answer you should be able to write without hints.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Second (Nth) highest distinct value: DENSE_RANK() in a CTE, or MAX(x) WHERE x < (SELECT MAX(x) ...), or SELECT DISTINCT ... ORDER BY x DESC LIMIT 1 OFFSET n-1. Plain ORDER BY ... OFFSET 1 is wrong when the top value is tied.
- Duplicates: SELECT email, COUNT() FROM users GROUP BY email HAVING COUNT() > 1. Delete duplicates but keep one: keep MIN(id) per email (or ROW_NUMBER() > 1 -> delete).
- No match (anti-join): customers without orders via LEFT JOIN ... WHERE o.id IS NULL, or NOT EXISTS.
- Top N per group and latest row per group: ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) then filter; Postgres also has DISTINCT ON.
- Running totals and day-over-day change: SUM() OVER (ORDER BY day) and LAG().
- Say your assumptions out loud: ties, NULLs, empty tables, and whether you need distinct values.
The red pen
Common traps: mistake → fix
Mistake: ORDER BY salary DESC LIMIT 1 OFFSET 1 is the second highest salary
Fix: with two people tied at the top it returns the top salary again.
Mistake: Deleting duplicates with DELETE ... WHERE id IN (duplicates)
Fix: that deletes every copy; keep one row per group.
Easy to hard
Questions interviewers ask, easy to hard
- Find the second highest salary. Now the third. Now per department.
- Find and delete duplicate users, keeping the oldest.
- Find workers who never applied to a shift.
- Find each user's most recent order.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.