skip to content

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
the eight questions, the tool that answers each, and the chapter behind it.

second highest salary, with ties

the org dataset rounds salaries to 1,000, so there are ties on purpose. the classic answer:

sqldb=org
SELECT max(salary) AS second_highest
FROM employees
WHERE salary < (SELECT max(salary) FROM employees);
output, from postgres 18.6
SELECT 1
second_highestnumeric
224000.00
(1 row)

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:

sqldb=org
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;
output, from postgres 18.6
SELECT 6
nametextsalarynumericrow_numberint8rankint8dense_rankint8
Fatima Lopez301000.00111
Chen Smith224000.00322
Mei Dubois224000.00222
Olivia Lopez220000.00443
Chen Jensen164000.00554
Noah Silva164000.00654
(6 rows)
nametextsalarynumericrow_numberint8rankint8dense_rankint8
Fatima Lopez301000.00111
Chen Smith224000.00322
Mei Dubois224000.00222
Olivia Lopez220000.00443
Chen Jensen164000.00554
Noah Silva164000.00654
(6 rows)
the top six salaries and the three ranking functions, from the block above. two people tie at 224,000. "the second highest salary" is dense_rank = 2: row_number picks one of the two arbitrarily, and rank skips from 2 to 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.

sqldb=org
SELECT DISTINCT salary
FROM (SELECT salary, dense_rank() OVER (ORDER BY salary DESC) AS r FROM employees) AS ranked
WHERE r = 2;
output, from postgres 18.6
SELECT 1
salarynumeric
224000.00
(1 row)
predict the output
SELECT salary FROM employees ORDER BY salary DESC OFFSET 1 LIMIT 1 returns?
sql
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):

sqldb=shop
SELECT email, count(*) AS n
FROM customers
GROUP BY email
HAVING count(*) > 1
ORDER BY n DESC, email;
output, from postgres 18.6
SELECT 1
emailtextnint8
null46
(1 row)

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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 2
idint4nametextemailtext
4Zoë MartinZoe.Martin@Example.com
5Zoe Martinzoe.martin@example.com
(2 rows)

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:

don'tdefault frame
sqldb=shop
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;
output, from postgres 18.6
SELECT 5
idint4daydaterunningint8
12025-07-0127
22025-07-0127
32025-07-0127
42025-07-0127
52025-07-0127
(5 rows)
doROWS, and a tiebreaker
sqldb=shop
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;
output, from postgres 18.6
SELECT 5
idint4daydaterunningint8
12025-07-011
22025-07-012
32025-07-013
42025-07-014
52025-07-015
(5 rows)

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:

sqldb=events
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;
output, from postgres 18.6
SELECT 18
daydaternint8islanddate
2026-04-2112026-04-20
2026-04-2222026-04-20
2026-04-2332026-04-20
2026-04-2442026-04-20
2026-04-2552026-04-20
2026-04-2662026-04-20
2026-04-2772026-04-20
2026-04-2882026-04-20
2026-04-2992026-04-20
2026-04-30102026-04-20
2026-05-01112026-04-20
2026-05-02122026-04-20
2026-05-03132026-04-20
2026-05-04142026-04-20
2026-05-06152026-04-21
2026-05-07162026-04-21
2026-05-08172026-04-21
2026-05-09182026-04-21
(18 rows)
daydaternint8islanddate
2026-04-2112026-04-20
2026-04-2222026-04-20
2026-04-2332026-04-20
2026-04-2442026-04-20
2026-04-2552026-04-20
2026-04-2662026-04-20
2026-04-2772026-04-20
2026-04-2882026-04-20
2026-04-2992026-04-20
2026-04-30102026-04-20
2026-05-01112026-04-20
2026-05-02122026-04-20
2026-05-03132026-04-20
2026-05-04142026-04-20
2026-05-06152026-04-21
2026-05-07162026-04-21
2026-05-08172026-04-21
2026-05-09182026-04-21
(18 rows)
user 17's days from the block above, shaded by island. the 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:

sqldb=events
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;
output, from postgres 18.6
SELECT 5
user_idint4streak_daysint8
147
247
347
547
144
(5 rows)

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):

sqldb=org
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;
output, from postgres 18.6
SELECT 16
depttextnametextsalarynumericrint8
designNoah Silva164000.001
designLiam Cohen123000.002
engineeringFatima Lopez301000.001
engineeringChen Smith224000.002
engineeringMei Dubois224000.002
financeLeila Larsen162000.001
financeKenji Cohen123000.002
peopleChen Jensen164000.001
peopleNoah Novak124000.002
productOlivia Singh161000.001
productIvan Smith123000.002
salesValentina Haddad164000.001
salesKenji Larsen161000.002
supportValentina Okafor160000.001
supportAmelia Romano124000.002
supportChen Novak124000.002
(16 rows)

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).

sqldb=shop
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;
output, from postgres 18.6
SELECT 6
statustextq3_2025int8q4_2025int8q1_2026int8q2_2026int8
cancelled99846668
delivered2423244123982090
paid00062
placed00051
refunded24232922
shipped000120
(6 rows)

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:

sqldb=org
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;
output, from postgres 18.6
SELECT 7
depttextpeopleint8meannumericmedianfloat8median_discnumeric
design40836507300073000.00
engineering84911907300073000.00
finance131076159900099000.00
people131076159700097000.00
product40835257300073000.00
sales80837007300073000.00
support29875177300073000.00
(7 rows)

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):

sqldb=org
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;
output, from postgres 18.6
SELECT 6
firsttextsecondtextsalarynumericdept_idint4
Chen NovakAmelia Romano124000.005
Diego WongClara Nguyen97000.005
Olivia JensenJonas Santos96000.005
Olivia HansenTariq Novak95000.005
Olivia HansenYuna Larsen95000.005
Tariq NovakYuna Larsen95000.005
(6 rows)

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.

quick check
SELECT count(*) FROM a LEFT JOIN b ON ... WHERE b.x = 1 behaves like?

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.