Skip to the page

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.

The 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

  1. Find the second highest salary. Now the third. Now per department.
  2. Find and delete duplicate users, keeping the oldest.
  3. Find workers who never applied to a shift.
  4. Find each user's most recent order.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview