SQL interview questions
second highest salary, duplicates, running totals, streaks. the classics, and the answer that lands.
- address
- everything.deep_dives.sql_interview
- part
- part 18, deep dives and interviews
- chapter
- chapter 6 of 10
- reading time
- 11 min
the SQL round is about eight questions in different clothes: second highest, duplicates, running totals, streaks, top n per group, pivot, median and a self join. each has an answer that lands, and a trap the interviewer is waiting for: ties, NULLs, or a frame you didn't know you had.
all of them below, runnable, on the book's datasets.
the picture
you know how interview SQL questions feel like puzzles you either know or don't? there are fewer of them than it seems. almost every one is a window function, a GROUP BY with HAVING, or a join of a table to itself, and almost every trap is about ties or NULLs.
think of a cookbook with eight recipes. once you know them, a "new" question is one recipe with the names changed (salaries become scores, employees become players). the interviewer isn't checking that you've seen it, they're checking that you ask "what about ties?" before they do.
- second highest, nth highestdense_rank(), or DISTINCT + OFFSET: ties decide which
- duplicatesGROUP BY ... HAVING count(*) > 1, on a normalized key; NULLs group together
- running totalssum() OVER (ORDER BY ...): the default frame includes ties
- streaksgaps and islands: date minus row_number() is constant inside a streak
- top n per groupa ranking function PARTITION BY the group, filtered outside
- pivotcount(*) FILTER (WHERE ...) per column
- medianpercentile_cont(0.5) WITHIN GROUP (ORDER BY ...), not avg()
- self jointhe table twice, with aliases, and a condition so pairs aren't counted twice
second highest salary, with ties
the org dataset rounds salaries to 1,000, so there are ties on purpose. the classic answer:
SELECT max(salary) AS second_highest
FROM employees
WHERE salary < (SELECT max(salary) FROM employees);| second_highestnumeric |
|---|
| 224000.00 |
224,000. it lands, and it handles ties at the top (two people at the max would both be excluded). but it doesn't generalize to "third" or "nth", and the interviewer's follow-up is always "now the nth". the window version does:
SELECT name, salary,
row_number() OVER w AS row_number,
rank() OVER w AS rank,
dense_rank() OVER w AS dense_rank
FROM employees
WINDOW w AS (ORDER BY salary DESC)
ORDER BY salary DESC, name
LIMIT 6;| nametext | salarynumeric | row_numberint8 | rankint8 | dense_rankint8 |
|---|---|---|---|---|
| Fatima Lopez | 301000.00 | 1 | 1 | 1 |
| Chen Smith | 224000.00 | 3 | 2 | 2 |
| Mei Dubois | 224000.00 | 2 | 2 | 2 |
| Olivia Lopez | 220000.00 | 4 | 4 | 3 |
| Chen Jensen | 164000.00 | 5 | 5 | 4 |
| Noah Silva | 164000.00 | 6 | 5 | 4 |
| nametext | salarynumeric | row_numberint8 | rankint8 | dense_rankint8 |
|---|---|---|---|---|
| Fatima Lopez | 301000.00 | 1 | 1 | 1 |
| Chen Smith | 224000.00 | 3 | 2 | 2 |
| Mei Dubois | 224000.00 | 2 | 2 | 2 |
| Olivia Lopez | 220000.00 | 4 | 4 | 3 |
| Chen Jensen | 164000.00 | 5 | 5 | 4 |
| Noah Silva | 164000.00 | 6 | 5 | 4 |
so the answer that lands is WHERE dense_rank = n in an outer query (ranking): "the nth highest distinct salary". if they mean "the nth person", it's row_number with a tiebreaker. ask which. that's the whole point of the question.
SELECT DISTINCT salary
FROM (SELECT salary, dense_rank() OVER (ORDER BY salary DESC) AS r FROM employees) AS ranked
WHERE r = 2;| salarynumeric |
|---|
| 224000.00 |
SELECT salary FROM employees ORDER BY salary DESC OFFSET 1 LIMIT 1;duplicates
"find customers with the same email". the first answer is a GROUP BY with HAVING (HAVING):
SELECT email, count(*) AS n
FROM customers
GROUP BY email
HAVING count(*) > 1
ORDER BY n DESC, email;| emailtext | nint8 |
|---|---|
| null | 46 |
two traps in one result. the 46 customers with no email came back as one "duplicate" group: GROUP BY puts all NULLs together, though NULL = NULL isn't true (NULL and three-valued logic). and Zoë and Zoe Martin are missing: Zoe.Martin@Example.com and zoe.martin@example.com are different strings. normalize the key and drop the NULLs, and return the rows, not just the counts:
SELECT id, name, email
FROM (SELECT id, name, email, count(*) OVER (PARTITION BY lower(email)) AS n
FROM customers WHERE email IS NOT NULL) AS c
WHERE n > 1
ORDER BY lower(email), id;| idint4 | nametext | emailtext |
|---|---|---|
| 4 | Zoë Martin | Zoe.Martin@Example.com |
| 5 | Zoe Martin | zoe.martin@example.com |
the follow-up is "delete the duplicates, keep the oldest": DELETE ... WHERE id NOT IN (SELECT min(id) ... GROUP BY lower(email)), or better, a row_number partitioned by the key and a DELETE of every row numbered above 1. and then add a unique index on lower(email) so it can't happen again (NOT NULL, CHECK and UNIQUE).
running totals
a running total is sum() OVER (ORDER BY ...) (LAG, LEAD and running totals). the trap is the frame you didn't write. with ORDER BY and no frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and RANGE includes the current row's peers, every row with the same ORDER BY value:
SELECT id, (ordered_at AT TIME ZONE 'UTC')::date AS day,
count(*) OVER (ORDER BY (ordered_at AT TIME ZONE 'UTC')::date) AS running
FROM orders
ORDER BY ordered_at, id
LIMIT 5;| idint4 | daydate | runningint8 |
|---|---|---|
| 1 | 2025-07-01 | 27 |
| 2 | 2025-07-01 | 27 |
| 3 | 2025-07-01 | 27 |
| 4 | 2025-07-01 | 27 |
| 5 | 2025-07-01 | 27 |
SELECT id, (ordered_at AT TIME ZONE 'UTC')::date AS day,
count(*) OVER (ORDER BY (ordered_at AT TIME ZONE 'UTC')::date, id
ROWS UNBOUNDED PRECEDING) AS running
FROM orders
ORDER BY ordered_at, id
LIMIT 5;| idint4 | daydate | runningint8 |
|---|---|---|
| 1 | 2025-07-01 | 1 |
| 2 | 2025-07-01 | 2 |
| 3 | 2025-07-01 | 3 |
| 4 | 2025-07-01 | 4 |
| 5 | 2025-07-01 | 5 |
every order placed on the same day is a peer, so with the default frame each of them gets the day's whole count at once, the total after adding all of them. that might be what you want (a total "as of that day"); usually it's a bug. a unique ORDER BY plus ROWS makes each row add exactly one row (window frames).
streaks: gaps and islands
"find each user's longest streak of consecutive active days". the trick: number each user's days in order. inside a run of consecutive days, the date and the row number go up together, so date minus row number is the same for every day of the streak, and changes after a gap (gaps and islands). user 17 is active every day for 30 days from april 21, except may 5:
WITH days AS (
SELECT DISTINCT (occurred_at AT TIME ZONE 'UTC')::date AS day
FROM events WHERE user_id = 17 AND occurred_at >= '2026-04-21'
)
SELECT day,
row_number() OVER (ORDER BY day) AS rn,
day - row_number() OVER (ORDER BY day)::int AS island
FROM days
ORDER BY day
LIMIT 18;| daydate | rnint8 | islanddate |
|---|---|---|
| 2026-04-21 | 1 | 2026-04-20 |
| 2026-04-22 | 2 | 2026-04-20 |
| 2026-04-23 | 3 | 2026-04-20 |
| 2026-04-24 | 4 | 2026-04-20 |
| 2026-04-25 | 5 | 2026-04-20 |
| 2026-04-26 | 6 | 2026-04-20 |
| 2026-04-27 | 7 | 2026-04-20 |
| 2026-04-28 | 8 | 2026-04-20 |
| 2026-04-29 | 9 | 2026-04-20 |
| 2026-04-30 | 10 | 2026-04-20 |
| 2026-05-01 | 11 | 2026-04-20 |
| 2026-05-02 | 12 | 2026-04-20 |
| 2026-05-03 | 13 | 2026-04-20 |
| 2026-05-04 | 14 | 2026-04-20 |
| 2026-05-06 | 15 | 2026-04-21 |
| 2026-05-07 | 16 | 2026-04-21 |
| 2026-05-08 | 17 | 2026-04-21 |
| 2026-05-09 | 18 | 2026-04-21 |
| daydate | rnint8 | islanddate |
|---|---|---|
| 2026-04-21 | 1 | 2026-04-20 |
| 2026-04-22 | 2 | 2026-04-20 |
| 2026-04-23 | 3 | 2026-04-20 |
| 2026-04-24 | 4 | 2026-04-20 |
| 2026-04-25 | 5 | 2026-04-20 |
| 2026-04-26 | 6 | 2026-04-20 |
| 2026-04-27 | 7 | 2026-04-20 |
| 2026-04-28 | 8 | 2026-04-20 |
| 2026-04-29 | 9 | 2026-04-20 |
| 2026-04-30 | 10 | 2026-04-20 |
| 2026-05-01 | 11 | 2026-04-20 |
| 2026-05-02 | 12 | 2026-04-20 |
| 2026-05-03 | 13 | 2026-04-20 |
| 2026-05-04 | 14 | 2026-04-20 |
| 2026-05-06 | 15 | 2026-04-21 |
| 2026-05-07 | 16 | 2026-04-21 |
| 2026-05-08 | 17 | 2026-04-21 |
| 2026-05-09 | 18 | 2026-04-21 |
island value holds steady through april and the first days of may, then jumps by one at may 6: the missing may 5 is the gap.then GROUP BY the island and count. for every user at once:
WITH days AS (
SELECT DISTINCT user_id, (occurred_at AT TIME ZONE 'UTC')::date AS day FROM events
), islands AS (
SELECT user_id, day - (row_number() OVER (PARTITION BY user_id ORDER BY day))::int AS island
FROM days
)
SELECT user_id, count(*) AS streak_days
FROM islands
GROUP BY user_id, island
ORDER BY streak_days DESC, user_id
LIMIT 5;| user_idint4 | streak_daysint8 |
|---|---|
| 1 | 47 |
| 2 | 47 |
| 3 | 47 |
| 5 | 47 |
| 1 | 44 |
the top streaks are 47 days: april 15 to may 31. nobody's streak crosses april 14, the one day the dataset has no events at all. the traps: count distinct days, not events (a user with three events on one day isn't on a three-day streak), and pick the time zone the "day" is in before you cast (timestamptz and time zones).
top n per group
"the top 2 earners in each department". rank inside each partition, filter outside, because a window function can't go in WHERE (top n per group):
SELECT dept, name, salary, r
FROM (SELECT d.name AS dept, e.name, e.salary,
dense_rank() OVER (PARTITION BY d.id ORDER BY e.salary DESC) AS r
FROM employees AS e JOIN departments AS d ON d.id = e.dept_id) AS ranked
WHERE r <= 2
ORDER BY dept, r, name;| depttext | nametext | salarynumeric | rint8 |
|---|---|---|---|
| design | Noah Silva | 164000.00 | 1 |
| design | Liam Cohen | 123000.00 | 2 |
| engineering | Fatima Lopez | 301000.00 | 1 |
| engineering | Chen Smith | 224000.00 | 2 |
| engineering | Mei Dubois | 224000.00 | 2 |
| finance | Leila Larsen | 162000.00 | 1 |
| finance | Kenji Cohen | 123000.00 | 2 |
| people | Chen Jensen | 164000.00 | 1 |
| people | Noah Novak | 124000.00 | 2 |
| product | Olivia Singh | 161000.00 | 1 |
| product | Ivan Smith | 123000.00 | 2 |
| sales | Valentina Haddad | 164000.00 | 1 |
| sales | Kenji Larsen | 161000.00 | 2 |
| support | Valentina Okafor | 160000.00 | 1 |
| support | Amelia Romano | 124000.00 | 2 |
| support | Chen Novak | 124000.00 | 2 |
with dense_rank, a tie can give a department more than two rows. that's the trap again: "top 2 people" (row_number, plus a tiebreaker) and "the people with the top 2 salaries" (dense_rank) are different questions. postgres also has a LATERAL version (FROM departments CROSS JOIN LATERAL (… ORDER BY salary DESC LIMIT 2)), which is the fast one when there's an index on (dept_id, salary) (LATERAL joins).
pivot
"orders per status, one column per quarter": FILTER on an aggregate makes each column (FILTER and pivoting).
SELECT status,
count(*) FILTER (WHERE ordered_at < '2025-10-01') AS q3_2025,
count(*) FILTER (WHERE ordered_at >= '2025-10-01' AND ordered_at < '2026-01-01') AS q4_2025,
count(*) FILTER (WHERE ordered_at >= '2026-01-01' AND ordered_at < '2026-04-01') AS q1_2026,
count(*) FILTER (WHERE ordered_at >= '2026-04-01') AS q2_2026
FROM orders
GROUP BY status
ORDER BY status;| statustext | q3_2025int8 | q4_2025int8 | q1_2026int8 | q2_2026int8 |
|---|---|---|---|---|
| cancelled | 99 | 84 | 66 | 68 |
| delivered | 2423 | 2441 | 2398 | 2090 |
| paid | 0 | 0 | 0 | 62 |
| placed | 0 | 0 | 0 | 51 |
| refunded | 24 | 23 | 29 | 22 |
| shipped | 0 | 0 | 0 | 120 |
the trap: columns have to be known when you write the query. a pivot whose columns come from the data (one per product, say) needs dynamic SQL or the application. CASE WHEN ... THEN 1 END inside count() is the portable spelling; FILTER is standard SQL that postgres supports and mysql doesn't.
median
avg() isn't the median. the median is an ordered-set aggregate:
SELECT d.name AS dept,
count(*) AS people,
round(avg(e.salary)) AS mean,
percentile_cont(0.5) WITHIN GROUP (ORDER BY e.salary) AS median,
percentile_disc(0.5) WITHIN GROUP (ORDER BY e.salary) AS median_disc
FROM employees AS e JOIN departments AS d ON d.id = e.dept_id
GROUP BY d.name
ORDER BY d.name;| depttext | peopleint8 | meannumeric | medianfloat8 | median_discnumeric |
|---|---|---|---|---|
| design | 40 | 83650 | 73000 | 73000.00 |
| engineering | 84 | 91190 | 73000 | 73000.00 |
| finance | 13 | 107615 | 99000 | 99000.00 |
| people | 13 | 107615 | 97000 | 97000.00 |
| product | 40 | 83525 | 73000 | 73000.00 |
| sales | 80 | 83700 | 73000 | 73000.00 |
| support | 29 | 87517 | 73000 | 73000.00 |
the mean sits above the median in most departments: one director's salary pulls the average up and barely moves the median. that's why "median" is asked: it tests whether you know they differ. percentile_cont interpolates between the two middle values when the count is even; percentile_disc returns an actual value from the data. say which you mean.
the self join
"find pairs of employees in the same department with the same salary". the table twice, with aliases (self joins):
SELECT a.name AS first, b.name AS second, a.salary, a.dept_id
FROM employees AS a
JOIN employees AS b
ON b.dept_id = a.dept_id AND b.salary = a.salary AND b.id > a.id
WHERE a.dept_id = 5
ORDER BY a.salary DESC, a.id, b.id
LIMIT 6;| firsttext | secondtext | salarynumeric | dept_idint4 |
|---|---|---|---|
| Chen Novak | Amelia Romano | 124000.00 | 5 |
| Diego Wong | Clara Nguyen | 97000.00 | 5 |
| Olivia Jensen | Jonas Santos | 96000.00 | 5 |
| Olivia Hansen | Tariq Novak | 95000.00 | 5 |
| Olivia Hansen | Yuna Larsen | 95000.00 | 5 |
| Tariq Novak | Yuna Larsen | 95000.00 | 5 |
the trap is b.id > a.id. with b.id <> a.id, every pair comes back twice (a, b and b, a). with nothing at all, everyone also pairs with themselves. the classic sibling of this question, "employees who earn more than their manager", is the same join on b.id = a.manager_id; in org it returns nothing, because salaries are set by level, and saying "an empty result is an answer" is a fine thing to say out loud.
keylines
- ties: dense_rank for "nth value", row_number plus a tiebreaker for "nth row". ask which.
- duplicates: GROUP BY a normalized key, HAVING count(*) > 1, and drop the NULLs first.
- running totals: the default frame includes peers. ROWS and a unique ORDER BY.
- streaks: date minus row_number is constant inside a streak.
- median is percentile_cont(0.5) WITHIN GROUP, never avg().
- self joins: alias both sides, and b.id > a.id so each pair comes back once.