SQL interview problems
Solve ranking, aggregation and join puzzles quickly.
By Invicly Tech, , in Interview Preparation. About 12 minutes to read.
In short
SQL interview problems focus on ranking, aggregation and joins, often timed. Recognising which window function or join pattern fits is most of the work.
Explained simply
SQL interview problems look different each time, but most use the same few patterns: group and count, join two tables, rank rows, compare a row with the row before it, or find rows that have no match. Once you can spot the pattern, writing the query is quick.
Before writing anything, ask what one row of the answer should represent. One row per customer? Per day? Per department? This is called the grain. Most wrong answers come from mixing grains, for example joining orders to items and then counting orders twice.
Window functions are the most powerful tool here. They calculate something across a group of rows, like a rank or a running total, but keep every row in the result. GROUP BY, on the other hand, squashes each group into one row.
Interviewers also test edge cases. What if two people have the same salary? What if there is no second highest? What if a column has NULLs? Saying these out loud, even before you are asked, shows care and experience.
Press Play on a diagram to walk through it one step at a time.
- 1, 2, 3, 4
- Always unique
- Pick exactly one row per group
- 1, 2, 2, 4
- Ties share, then a gap
- Competition-style ranking
- 1, 2, 2, 3
- Ties share, no gap
- Nth highest distinct value
- 1Read the schema
Keys, nullable columns, duplicates
- 2State the grain
One output row per what?
- 3Pick the pattern
Join, GROUP BY, window function or self-join
- 4Write in CTEs
Small named steps, easy to check
- 5Test edge cases
Ties, NULLs, empty results
- Top N or Nth
- DENSE_RANK for distinct values
- ROW_NUMBER for exactly one per group
- Compare to previous row
- LAG or LEAD
- Self-join on date + 1
- Never or missing
- LEFT JOIN ... IS NULL
- NOT EXISTS
- Totals and ratios
- GROUP BY with HAVING
- SUM(CASE WHEN ...) or FILTER
- Streaks
- Date minus ROW_NUMBER
- Running SUM of new-streak flags
In depth
The logical order a query runs in
SQL is written SELECT first, but it is evaluated in a different order. First FROM and JOIN build the rows. Then WHERE filters individual rows. Then GROUP BY forms groups, and HAVING filters groups. Then SELECT computes output columns, including window functions. Then DISTINCT, then ORDER BY, then LIMIT or OFFSET.
This order explains many errors. You cannot use a window function in WHERE, because windows are computed after WHERE; wrap the query in a CTE and filter outside. You cannot filter an aggregate in WHERE; use HAVING. In standard SQL you cannot use a SELECT alias in WHERE either, though PostgreSQL and MySQL do allow aliases in ORDER BY. The planner may physically run things differently, but the result must match this logical order.
- 1FROM and JOIN
Build the combined rows
- 2WHERE
Filter single rows
- 3GROUP BY and HAVING
Make groups, filter groups
- 4SELECT and windows
Compute columns, ranks, totals
- 5DISTINCT and ORDER BY
Remove duplicates, sort
- 6LIMIT
Keep the first N rows
Window functions beyond ranking
A window function has the form f() OVER (PARTITION BY ... ORDER BY ...). PARTITION BY splits rows into groups that do not see each other; ORDER BY sets the order inside each group. Ranking functions (ROW_NUMBER, RANK, DENSE_RANK, NTILE) need ORDER BY.
LAG(col) and LEAD(col) read the previous or next row, which solves day-over-day change and "consecutive" problems. SUM(amount) OVER (PARTITION BY user_id ORDER BY day) gives a running total. Watch the frame: with ORDER BY, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which treats rows with equal ORDER BY values as one peer group. For a true row-by-row running total or a 7-day moving average, say ROWS BETWEEN 6 PRECEDING AND CURRENT ROW explicitly.
An aggregate with an empty OVER (), like COUNT(*) OVER (), adds the total to every row, which helps compute percentages of the whole.
- LAG(x, 1, 0) gives a default of 0 for the first row
- FIRST_VALUE and LAST_VALUE depend on the frame; LAST_VALUE often needs ROWS BETWEEN ... UNBOUNDED FOLLOWING
- Percentage of total: amount * 100.0 / SUM(amount) OVER ()
Anti-joins and the NOT IN trap
"Find customers who never ordered" is an anti-join: rows in A with no match in B. Two safe ways: LEFT JOIN orders o ON ... WHERE o.id IS NULL, or WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id). Both are clear and well optimised.
The dangerous one is WHERE c.id NOT IN (SELECT customer_id FROM orders). If even one customer_id in orders is NULL, the comparison with NULL gives unknown, and the whole query returns zero rows. Interviewers love this trap. Prefer NOT EXISTS, or add WHERE customer_id IS NOT NULL inside the subquery.
Also know the join row counts: an inner join drops unmatched rows, a left join keeps all left rows, and a one-to-many join multiplies rows, so aggregate before joining or count DISTINCT when needed.
Gaps and islands: finding consecutive runs
Problems like "users who logged in three days in a row" or "find streaks" are gaps-and-islands problems. The trick: number each user's rows by date with ROW_NUMBER, then subtract that number (as days) from the date. For consecutive dates, the date and the row number grow together, so the difference stays the same. Every run of consecutive days shares one constant value, called the island key.
Then GROUP BY user and island key, and count the rows in each group to get streak lengths. Remove duplicate dates first (SELECT DISTINCT user_id, login_date), or repeats will break the pattern. LAG is an alternative: mark a row as a new streak when the date is not the previous date plus one, then a running SUM of those marks gives the island id.
- Jan 1
- Jan 2
- Jan 3
- Jan 6
- Jan 7
- 1
- 2
- 3
- 4
- 5
- Dec 31 (island A)
- Dec 31 (island A)
- Dec 31 (island A)
- Jan 2 (island B)
- Jan 2 (island B)
A routine for timed SQL rounds
Timed rounds are usually 15 to 30 minutes per problem. Spend the first two minutes on the schema: primary keys, nullable columns, whether duplicates exist. Say the grain out loud. Then write the query as a chain of small CTEs, each doing one step, and run each step if the platform allows it. That makes debugging fast.
Check these edge cases before you say done: ties (RANK or DENSE_RANK instead of ROW_NUMBER?), NULLs in joins and aggregates (COUNT(col) skips NULLs, AVG ignores them), an empty result that must return NULL, and integer division (in PostgreSQL 7 / 2 is 3, so multiply by 1.0 or cast). If the question names a database, use its functions: DATE_TRUNC in PostgreSQL, DATE_FORMAT in MySQL.
Practise on LeetCode's SQL 50, DataLemur or StrataScratch, timing yourself to around 10 minutes for easy and 20 for medium.
- Ask: one output row per what?
- Write CTEs, test each one
- Check ties, NULLs, empty results, integer division
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Practice ranking with ROW_NUMBER and DENSE_RANK~1h
- 2Practice: Second Highest Salary, Nth Highest~1h
- 3Solve aggregation and self-join puzzles~1h
- 4Practise timed SQL problems~1h
Key points
- Nth highest distinct salary: DENSE_RANK() = N, returning NULL if none exists.
- Top N per group: ROW_NUMBER() OVER (PARTITION BY group ORDER BY value DESC).
- Self-joins compare rows in one table, such as employees earning more than their manager.
- COUNT(col) skips NULLs while COUNT(*) counts every row.
Key terms
Tap a card to flip it. 0/4 known
Examples
-- Second highest distinct salary (NULL if none)
SELECT MAX(salary) AS second_highest
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) ranked
WHERE rnk = 2;
-- Employees earning more than their manager
SELECT e.name
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;Top 3 distinct salaries per department
Classic problem (LeetCode 185, Department Top Three Salaries). Step 1: grain is one row per employee who qualifies. Step 2: ties matter, the question says "top three unique salaries", so use DENSE_RANK, not ROW_NUMBER. Step 3: partition by department and order by salary descending. Step 4: filter in an outer query because window results are not available in WHERE. Step 5: join departments for the name. Edge case: a department with only two distinct salaries just returns those.
WITH ranked AS (
SELECT e.name, e.salary, e.department_id,
DENSE_RANK() OVER (PARTITION BY e.department_id
ORDER BY e.salary DESC) AS rnk
FROM employees e
)
SELECT d.name AS department, r.name AS employee, r.salary
FROM ranked r
JOIN departments d ON d.id = r.department_id
WHERE r.rnk <= 3
ORDER BY d.name, r.salary DESC;Day-over-day revenue change with conditional totals
Prompt: show daily revenue, the change from the previous day, and revenue from refunds separately. Step 1: aggregate orders to one row per day first, because LAG must compare days, not orders. Step 2: use conditional aggregation to split sales and refunds in one pass. Step 3: apply LAG on the daily rows. Step 4: note that the first day has no previous value, so the change is NULL, which is honest. If days can be missing, mention joining to a generated calendar (generate_series in PostgreSQL).
WITH daily AS (
SELECT DATE_TRUNC('day', created_at)::date AS day,
SUM(amount) FILTER (WHERE kind = 'sale') AS sales,
SUM(amount) FILTER (WHERE kind = 'refund') AS refunds
FROM orders
GROUP BY 1
)
SELECT day, sales, refunds,
sales - LAG(sales) OVER (ORDER BY day) AS change_vs_prev
FROM daily
ORDER BY day;Quick reference
- Logical order: FROM, WHERE, GROUP BY, HAVING, SELECT (windows), DISTINCT, ORDER BY, LIMIT
- Filter on a window function in an outer query or CTE, never in the same WHERE
- Nth highest distinct: DENSE_RANK() = N, or SELECT DISTINCT ... ORDER BY ... LIMIT 1 OFFSET N-1
- Duplicates: GROUP BY col HAVING COUNT(*) > 1
- Never matched: LEFT JOIN ... WHERE right.id IS NULL, or NOT EXISTS (avoid NOT IN with NULLs)
- Running total: SUM(x) OVER (PARTITION BY k ORDER BY d ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
- Streaks: date minus ROW_NUMBER() gives a constant key per consecutive run
- PostgreSQL integer division truncates: use 100.0 * a / b for percentages
Common mistakes
- Using ROW_NUMBER for Nth highest, which breaks on ties.
- Forgetting the no-result case should return NULL.
- Filtering on a window function in WHERE; wrap it in a subquery or CTE.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
From employees(id, name, salary), return the second highest distinct salary as second_highest, or NULL if there is none, without window functions.
- Exercise 2medium
From logins(user_id, login_date), list users who logged in on at least 3 consecutive days.
- Exercise 3hard
Delete duplicate rows from users(id, email), keeping only the row with the smallest id for each email. Write it for PostgreSQL.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between WHERE and HAVING?
- WHERE filters individual rows before grouping. HAVING filters groups after GROUP BY, so it can use aggregates like COUNT(*) or SUM.
- When should I use ROW_NUMBER instead of DENSE_RANK?
- Use ROW_NUMBER when you need exactly one row per group, such as the latest order per customer. Use DENSE_RANK when ties should share a position, such as the top three distinct salaries.
- Where can I practise SQL interview questions?
- LeetCode's SQL 50 list, DataLemur and StrataScratch have real interview problems with checkers. Time yourself and run each CTE step separately to build speed.
- Are CTEs slower than subqueries?
- In modern PostgreSQL (12 and later) simple CTEs are usually inlined, so they perform like subqueries. Use them for readability, and check EXPLAIN if performance matters.