14 SQL questions experienced candidates face, with working queries, the follow-ups interviewers push on, and the NULL, tie and index traps.
Most SQL interview questions for 5 years experience are not harder syntax. They test whether you can predict what the database will do: which rows a window function keeps when values tie, why NOT IN returns nothing, why an index is ignored, what happens when two transactions touch the same rows. Expect to write queries live and then defend them. Below are 14 questions in three groups (writing queries, performance, design and concurrency), each with what it tests, a working query in PostgreSQL syntax, and the follow-up that separates an experienced answer from a junior one.
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.
Before the round: know the editor
If your live round runs in CoderPad, its PostgreSQL mode runs PostgreSQL 12.4 and its MySQL mode runs MySQL 8.0. Both preload the same sample tables: employees (with salary and department_id), departments, projects and the join table employees_projects. Practise against that schema, and ask which engine you are on before using version-specific syntax.
Writing queries
1. Find the highest-paid employee in each department.
Tests: window functions and ties.
SELECT department_id, first_name, last_name, salary
FROM (
SELECT e.*,
DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
FROM employees e
) ranked
WHERE rnk = 1;Say why you chose the function. ROW_NUMBER() returns exactly one row per department and picks arbitrarily between equal salaries. RANK() leaves gaps after ties (1, 1, 3); DENSE_RANK() does not (1, 1, 2). For "the Nth highest salary", DENSE_RANK() with rnk = N is usually what the interviewer means.
2. Delete duplicate rows, keeping one.
Tests: which row survives, and doing it safely.
WITH ranked AS (
SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
FROM users
)
DELETE FROM users
WHERE id IN (SELECT id FROM ranked WHERE rn > 1);ORDER BY id keeps the oldest row; say so. The experienced additions: run the SELECT first inside a transaction to check the count, then add a unique constraint so duplicates cannot return.
3. List employees with no project.
Tests: the NOT IN null trap.
SELECT e.id, e.first_name
FROM employees e
WHERE NOT EXISTS (
SELECT 1 FROM employees_projects ep WHERE ep.employee_id = e.id
);The tempting version, WHERE e.id NOT IN (SELECT employee_id FROM employees_projects), returns no rows at all if any employee_id is null: with no match and a null in the list, NOT IN yields null, not true. NOT EXISTS only checks whether a row exists, so nulls do not affect it.
4. Running total and 7-day moving average.
Tests: window frames.
SELECT day, revenue,
SUM(revenue) OVER (ORDER BY day) AS running_total,
AVG(revenue) OVER (ORDER BY day
RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW) AS avg_7d
FROM daily_revenue;Two points candidates miss. The default frame is RANGE ... CURRENT ROW, which includes every row tied with the current one, so duplicate days share one running total. And ROWS BETWEEN 6 PRECEDING means seven rows, not seven days: if days are missing, the window silently stretches. A RANGE frame with an interval offset counts calendar days.
5. Find streaks of consecutive login days.
Tests: the gaps-and-islands pattern.
WITH days AS (
SELECT DISTINCT user_id, login_at::date AS d FROM logins
), grouped AS (
SELECT user_id, d,
d - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY d))::int AS grp
FROM days
)
SELECT user_id, MIN(d) AS streak_start, MAX(d) AS streak_end, COUNT(*) AS streak_days
FROM grouped
GROUP BY user_id, grp
ORDER BY streak_days DESC;Consecutive dates minus their row number give the same value, so each streak becomes one group. The DISTINCT matters: two logins on one day would otherwise break the streak. To keep only each user's longest streak, rank the groups as in question 1.
6. Show an employee's full management chain.
Tests: recursive CTEs.
WITH RECURSIVE chain AS (
SELECT id, manager_id, 1 AS depth FROM staff WHERE id = 42
UNION ALL
SELECT s.id, s.manager_id, c.depth + 1
FROM staff s JOIN chain c ON s.id = c.manager_id
WHERE c.depth < 20
)
SELECT * FROM chain;Name the two parts (the non-recursive starting row, then the recursive term that joins back to chain) and explain the depth limit: bad data with a cycle would otherwise recurse without end.
Performance
7. "This query got slow. Walk me through it."
Tests: method. Run EXPLAIN ANALYZE and compare estimated rows with actual rows at each node; a large gap can mean the planner's statistics are stale or too coarse, so run ANALYZE on the table and check again. Two details show experience: EXPLAIN ANALYZE really executes the statement, so wrap an UPDATE in BEGIN and ROLLBACK; and for nodes that run in loops, the reported time and rows are per loop.
8. Why isn't my index being used?
Tests: sargability. An index on email does not help WHERE lower(email) = 'a@b.com'; an index on the expression lower(email) does, at the cost of computing it on every insert. A B-tree can serve LIKE 'smi%' but not LIKE '%son', and outside the C locale even the first needs an index with a pattern operator class such as text_pattern_ops.
9. What column order for a composite index on `WHERE customer_id = $1 AND created_at >= $2`?
Tests: how B-trees narrow a scan. Put the equality column first: (customer_id, created_at). Equality on leading columns plus a range on the next column limits the part of the index scanned; with created_at first, customer_id is only checked inside a wider range. Add INCLUDE (total) if the query also reads total, so it can be an index-only scan, and mention the cost: a bigger index.
10. How would you paginate a large table?
Tests: knowing why OFFSET degrades.
SELECT id, created_at, total
FROM orders
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 50;OFFSET 100000 still makes the database fetch and discard 100,000 rows, and rows inserted between requests cause duplicates. Keyset pagination filters past the last row seen instead. It needs a deterministic order (hence id as a tiebreaker) and gives up jumping straight to page N.
11. Is a CTE slower than a subquery?
Tests: whether you know your engine. In PostgreSQL, a non-recursive, side-effect-free WITH query referenced once can be folded into the main query and optimised with it. Referenced more than once, it is materialized by default: computed once as its own step and reused, without the outer query's filters pushed into it. MATERIALIZED and NOT MATERIALIZED override that choice.
Design and concurrency
12. Explain isolation levels, and what your database uses by default.
Tests: knowing that defaults differ. PostgreSQL and SQL Server default to Read Committed; MySQL's InnoDB defaults to Repeatable Read. PostgreSQL's Read Uncommitted behaves like Read Committed, and its Repeatable Read does not allow phantom reads. The experienced answer names the anomaly the code must prevent, such as two sessions reading a balance and both writing, then picks a fix: a stricter level or a row lock with SELECT ... FOR UPDATE.
13. How do you deal with deadlocks?
Tests: prevention over firefighting. PostgreSQL detects a deadlock and aborts one of the transactions, and which one is hard to predict. Prevent them by taking locks in a consistent order across the application, taking the most restrictive lock you will need first, and keeping transactions short. Then retry transactions that fail with a deadlock error.
14. You need an index on a large, busy production table. How?
Tests: operational care. A plain CREATE INDEX in PostgreSQL blocks inserts, updates and deletes (not reads) until it finishes. CREATE INDEX CONCURRENTLY avoids that but scans the table twice, takes longer, cannot run inside a transaction block, and on failure leaves an invalid index that still slows writes. Check for it, drop it and retry.
You may get a behavioural question too, such as "Tell me about a query you made faster." Bring a real one: the plan before and after, what you measured, what you changed and what it cost (more storage, slower writes).
A one-week plan
- Days 1-2: Questions 1 to 6 against the CoderPad sample tables or a local PostgreSQL, without looking at the answers. Say the edge cases aloud: ties, nulls, missing days.
- Day 3: Load a table with a million generated rows. Run questions 7 to 10 on it and read every plan.
- Day 4: Two terminal sessions: reproduce a deadlock, then a lost update, and fix both.
- Day 5: Write your "query I made faster" story with real numbers from your own work.
- Days 6-7: Timed problems you have not seen, explaining your approach before you type.
For the fundamentals underneath these, see our SQL joins interview questions and the SQL questions for three years of experience. If your role leans toward administration, the SQL DBA interview questions cover backups, replication and server tuning.
Verve AI's Coding Copilot captures a question from your screen and returns a solution in 21+ programming languages, SQL included, with quick actions such as Optimize, Edge Case and Complexity. It works best when the whole question, including constraints and examples, is visible in the capture.
Sources
- CoderPad PostgreSQL mode runs PostgreSQL 12.4, preloaded employees/departments/projects/employees_projects tables: https://coderpad.io/languages/postgresql/
- CoderPad MySQL mode runs MySQL 8.0, same sample tables: https://coderpad.io/languages/mysql/
- row_number, rank (with gaps), dense_rank (without gaps): https://www.postgresql.org/docs/current/functions-window.html
- NOT IN yields null when no match and a null is present; EXISTS depends only on whether rows are returned: https://www.postgresql.org/docs/current/functions-subquery.html
- Default window frame RANGE UNBOUNDED PRECEDING includes peers; ROWS counts rows; RANGE offset is an interval for date columns: https://www.postgresql.org/docs/current/sql-expressions.html
- Recursive WITH structure; folding of side-effect-free WITH queries referenced once; MATERIALIZED / NOT MATERIALIZED; DELETE in WITH: https://www.postgresql.org/docs/current/queries-with.html
- EXPLAIN ANALYZE executes the query, BEGIN/ROLLBACK for writes, estimated vs actual rows, per-loop values, ANALYZE statistics: https://www.postgresql.org/docs/current/using-explain.html
- Expression index on lower(col) and its write cost: https://www.postgresql.org/docs/current/indexes-expressional.html
- B-tree and LIKE: anchored constant patterns only; operator class needed outside the C locale: https://www.postgresql.org/docs/current/indexes-types.html
- Multicolumn B-tree: equality on leading columns plus inequality on the next column limit the scan: https://www.postgresql.org/docs/current/indexes-multicolumn.html
- INCLUDE non-key columns enable index-only scans and enlarge the index; CREATE INDEX CONCURRENTLY behaviour, transaction block restriction, invalid index on failure: https://www.postgresql.org/docs/current/sql-createindex.html
- OFFSET fetches skipped rows, duplicates on inserts, keyset needs deterministic order, no jumping to arbitrary pages: https://use-the-index-luke.com/no-offset
- PostgreSQL default Read Committed; Read Uncommitted behaves like Read Committed; Repeatable Read does not allow phantoms: https://www.postgresql.org/docs/current/transaction-iso.html
- InnoDB default isolation level is REPEATABLE READ: https://dev.mysql.com/doc/refman/8.4/en/innodb-transaction-isolation-levels.html
- SQL Server default is READ COMMITTED: https://learn.microsoft.com/en-us/sql/t-sql/statements/set-transaction-isolation-level-transact-sql
- Deadlock detection, unpredictable victim, consistent lock order, most restrictive lock first, short transactions, retry; row-level locks with SELECT FOR UPDATE: https://www.postgresql.org/docs/current/explicit-locking.html
- Coding Copilot captures from screen, 21+ languages including SQL, quick actions, full-question tip: https://docs.vervecopilot.com/features/coding-copilot
Ryan
CEO of Verve AI







