Ten scenario SQL questions mid-level candidates get, what each one tests, and a tested answer, plus the traps (NULLs, ties, outer joins) that sink answers.
With three to five years behind you, SQL interview questions stop being definitions. You get a table, a business question and a clock. The ten scenarios below cover what that round keeps coming back to: filtering before and after aggregation, NULLs, outer joins that quietly turn into inner joins, window functions for top-N, deduplication, running totals and streaks, and the "this query is slow" conversation. Each one says what the interviewer is checking and gives a short answer. Every query was run on a small sample dataset in SQLite 3.45; the one line that needs PostgreSQL syntax assumes login_date is a date column and is marked.
For how this fits into the whole loop, including the data modeling and pipeline design rounds, see our guide to passing the data engineer interview.
How the SQL round usually runs
Three formats come up, often in the same process. DataLemur's guide describes online assessments that give you about an hour for two or three hard questions; live screens, where the interviewer watches you write and expects you to think out loud; and take-home challenges with messier data and a longer timeframe, where the deliverable can include a written report or a presentation of your analysis. The same guide lists the topics that recur: basic commands, joins, window functions, database design and turning a business question into a query.
At the mid level, the difference is the follow-up. A correct first query earns the next question: what about ties, what about NULLs, what happens at ten million rows. The scenarios below are grouped the way those follow-ups tend to stack.
Round 1: correctness traps
1. Which customers placed more than three orders in 2025?
What it tests: whether you know that WHERE filters rows before grouping and HAVING filters groups after. PostgreSQL's tutorial calls this the fundamental difference between the two.
SELECT customer_id, COUNT(*) AS orders_2025
FROM orders
WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) > 3;Say why the date filter sits in WHERE: it shrinks the rows before the aggregate runs, and it does not need an aggregate. The half-open range (< '2026-01-01') also survives timestamp columns, where BETWEEN ... AND '2025-12-31' silently drops anything timestamped after 00:00 on 31 December.
2. How many customers have no email on file?
What it tests: three-valued logic. email = NULL is never true, because any ordinary comparison with NULL yields NULL. email = NULL never matches any row, so on a table that holds NULL and blank emails it returns 0.
SELECT COUNT(*)
FROM customers
WHERE email IS NULL OR TRIM(email) = '';The TRIM check is the mid-level touch: real data stores blanks as well as NULLs. Ask which the business counts as missing.
3. List every customer with their 2025 order count and revenue, including customers with none
What it tests: the most common outer-join bug. Put the date filter in WHERE and every customer without a 2025 order disappears, because WHERE runs after the join and their order columns are NULL. PostgreSQL's documentation puts it plainly: a restriction in ON is processed before the join, one in WHERE after, and that "matters a lot with outer joins".
SELECT c.customer_id,
COUNT(o.order_id) AS orders_2025,
COALESCE(SUM(o.amount), 0) AS revenue_2025
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id
AND o.order_date >= '2025-01-01'
AND o.order_date < '2026-01-01'
GROUP BY c.customer_id;Two more details interviewers look for. COUNT(o.order_id) returns 0 for a customer with no orders, while COUNT(*) returns 1, because it counts the NULL-padded row. And SUM over no rows is NULL, not 0, hence the COALESCE.
4. Which customers have never ordered?
What it tests: whether you reach for NOT IN and know why it fails. If the subquery returns a single NULL (a guest order with no customer ID, say), NOT IN returns no rows at all. The PostgreSQL wiki's "Don't Do This" page recommends NOT EXISTS instead, and notes that NOT IN (SELECT ...) also performs worse.
SELECT c.customer_id
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);A LEFT JOIN ... WHERE o.order_id IS NULL anti-join is also a good answer. Naming both shows range.
Round 2: window functions
Window functions keep every row while computing over a group, which is why they carry most mid-level questions. One rule trips people up under time pressure: they are allowed only in the SELECT list and ORDER BY, so filtering on one needs a subquery or CTE.
5. Return the top two salaries in each department
What it tests: partitioning, and whether you ask about ties before you type.
SELECT dept, emp_id, salary
FROM (
SELECT dept, emp_id, salary,
DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk
FROM employees
) ranked
WHERE rnk <= 2;The choice of function is the answer. ROW_NUMBER always returns exactly two rows and breaks ties arbitrarily. RANK leaves a gap after a tie and DENSE_RANK does not: with salaries of 200, 200 and 180, RANK gives 1, 1, 3 and returns two people, while DENSE_RANK gives 1, 1, 2 and returns all three. Ask whether "top two" means two people or two salary levels, then pick.
6. Remove duplicate users, keeping the most recent record per email
What it tests: the same pattern used for cleanup.
SELECT user_id, email, updated_at
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY email
ORDER BY updated_at DESC, user_id DESC) AS rn
FROM users_raw
) t
WHERE rn = 1;Here ROW_NUMBER is right because you want exactly one survivor. The second sort key makes the result deterministic when two rows share a timestamp. Mention it before the interviewer does.
7. Show a running total of daily sales
What it tests: window frames. With ORDER BY and no frame clause, the default frame runs from the start through the current row plus every row tied with it. So if two sales fall on the same day, both rows show the day's full total, not a row-by-row total.
SELECT sale_date,
SUM(SUM(amount)) OVER (ORDER BY sale_date) AS running_total
FROM daily_sales
GROUP BY sale_date;Aggregating to one row per day first makes the default frame correct. If the interviewer wants a row-level total, add ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW and a tiebreaker in the ORDER BY. Knowing why the two outputs differ is the point of the question.
8. Compute month-over-month revenue change
What it tests: LAG, and division safety.
SELECT month, revenue,
revenue - LAG(revenue) OVER (ORDER BY month) AS change,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS pct_change
FROM monthly_revenue;The first month has no previous row, so LAG returns NULL; say that this is expected. NULLIF(..., 0) stops a zero-revenue month from raising a division error, and 100.0 avoids integer division in databases that truncate.
9. Find each user's login streaks
What it tests: gaps and islands, the classic harder scenario. Consecutive dates minus their row number give the same value, so that value identifies the streak.
WITH days AS (
SELECT DISTINCT user_id, login_date FROM logins
),
grouped AS (
SELECT user_id, login_date,
-- PostgreSQL: login_date - (ROW_NUMBER() OVER (...))::int
julianday(login_date)
- ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) AS grp
FROM days
)
SELECT user_id, MIN(login_date) AS streak_start,
MAX(login_date) AS streak_end, COUNT(*) AS streak_days
FROM grouped
GROUP BY user_id, grp;The DISTINCT step matters: two logins on the same day would otherwise break the arithmetic. Walk the interviewer through three sample rows; this is the question where showing the trick beats reciting it.
Round 3: performance
10. This report query got slow. What do you do?
What it tests: a method, not a magic index. A strong answer runs in order:
- Read the plan. EXPLAIN shows the planner's estimates. EXPLAIN ANALYZE actually runs the query and shows real row counts and timings. On an UPDATE or DELETE that means the change really happens, so wrap it in a transaction and roll back. Saying that unprompted signals production experience.
- Compare estimates with actual rows. A large gap between estimated and actual rows is worth investigating: the planner's estimates come from sampled statistics, so stale statistics or a condition the planner cannot estimate well are common suspects.
- Check the index matches the predicate. A composite B-tree index on (customer_id, order_date) is most useful when the query constrains customer_id; a filter on order_date alone usually gets much less from it, though recent PostgreSQL versions can sometimes use skip scan when the leading column has few distinct values. And wrapping an indexed column in a function, like WHERE UPPER(last_name) = 'SMITH', stops a plain index on last_name from being used. The fix is an index on the expression, or a generated column.
- Name the cost. Every index adds work to each write and takes space. Say what you would measure before and after.
Answering out loud
The query is half the score. Before writing, ask four things: can there be ties, can the key columns be NULL, are there duplicates, and is the date column a date or a timestamp. Then name the pattern ("this is top-N per group") and build in readable CTEs. When you finish, test one edge case aloud: an empty group, a NULL key, a tie at the cutoff.
A one-week plan
- Days 1–2: questions 1–4 from memory on a blank editor, then break each with a NULL or an empty table.
- Days 3–4: questions 5–9; for each, write the ROW_NUMBER, RANK and DENSE_RANK versions and predict the difference before running them.
- Day 5: run EXPLAIN on your own queries against a table with a few hundred thousand rows; add and drop one index and compare plans.
- Day 6: two timed sets of two questions in 60 minutes, explaining aloud.
- Day 7: light review only.
Verve AI's Coding Copilot reads a question from a screen capture and returns a solution in 21+ languages, SQL included, and its Edge Case and Optimize quick actions map onto the follow-ups above. The SQL Interview Copilot page shows how it handles SQL rounds.
For narrower drills, see the SQL joins interview questions, SQL query questions for five years' experience and SQL DBA interview questions.
Sources
- Interview formats (online assessments of 2–3 questions in about an hour, live screens, take-homes) and recurring topics: https://datalemur.com/blog/sql-interview-guide
- WHERE filters rows before aggregation, HAVING filters groups after: https://www.postgresql.org/docs/current/tutorial-agg.html
- Comparisons with NULL yield NULL; use IS NULL: https://www.postgresql.org/docs/current/functions-comparison.html
- ON restrictions run before the join, WHERE after; "matters a lot with outer joins": https://www.postgresql.org/docs/current/queries-table-expressions.html
- COUNT(*) counts rows, COUNT(expr) counts non-null values; SUM of no rows is NULL: https://www.postgresql.org/docs/current/functions-aggregate.html
- NOT IN returns no rows when a NULL is present; use NOT EXISTS; NOT IN (SELECT ...) performs poorly: https://wiki.postgresql.org/wiki/Don%27t_Do_This
- Window functions keep rows; allowed only in SELECT and ORDER BY; default frame includes peers: https://www.postgresql.org/docs/current/tutorial-window.html
- ROW_NUMBER, RANK (with gaps), DENSE_RANK (without gaps), LAG returns NULL when no prior row: https://www.postgresql.org/docs/current/functions-window.html
- date - integer subtracts days in PostgreSQL: https://www.postgresql.org/docs/current/functions-datetime.html
- EXPLAIN vs EXPLAIN ANALYZE, side effects and the rollback pattern: https://www.postgresql.org/docs/current/using-explain.html
- Multicolumn B-tree indexes work best with constraints on the leading column: https://www.postgresql.org/docs/current/indexes-multicolumn.html
- A function on an indexed column prevents index use; index the expression instead: https://use-the-index-luke.com/sql/where-clause/functions/case-insensitive-search
- Coding Copilot: screen capture, SQL among 21+ languages, Edge Case and Optimize quick actions: https://docs.vervecopilot.com/features/coding-copilot
- Sample-data test of every query: run during drafting in SQLite 3.45.3 on 2026-10-18 (sql-sample-test.py in the page folder)
Ryan
CEO of Verve AI






