ExtraBrain Interview Questions
SQL Interview Questions for 2026, With Tested Queries
Short answer
Most SQL interview questions test whether your queries are correct on messy data, not whether you know keywords. Expect top-N-per-group with ROW_NUMBER, RANK and DENSE_RANK, running totals and window frames, LEFT JOIN filters that silently become inner joins, NOT IN with NULLs, gaps-and-islands streaks, duplicate detection, composite indexes and isolation levels. Explain ties and NULLs before the interviewer asks.
SQL interview questions with tested queries: window functions, ranking ties, joins, NULL traps, gaps and islands, indexes and isolation levels.
SQL rounds look easy until the data has ties, NULLs and duplicates, which is exactly the data interviewers bring. A query that returns the right rows on the happy path and the wrong rows when two people share a salary is a failed answer, even if it runs.
Every query below was run in SQLite against the sample tables in the first block, and each one notes where PostgreSQL differs. The concepts carry across databases; the PostgreSQL 19 documentation is the reference used for behavior.
CREATE TABLE employees (id INTEGER PRIMARY KEY, name TEXT, dept TEXT, salary INTEGER, manager_id INTEGER);INSERT INTO employees VALUES (1, 'Ada', 'eng', 200, NULL), (2, 'Grace', 'eng', 180, 1), (3, 'Linus', 'eng', 180, 1), (4, 'Margaret', 'eng', 150, 1), (5, 'Barbara', 'sales', 120, NULL), (6, 'Ken', 'sales', 110, 5);
CREATE TABLE orders (id INTEGER PRIMARY KEY, employee_id INTEGER, amount INTEGER, status TEXT);INSERT INTO orders VALUES (1, 2, 50, 'paid'), (2, 2, 30, 'refunded'), (3, 6, 70, 'paid');
CREATE TABLE logins (user_id INTEGER, day TEXT);INSERT INTO logins VALUES (1, '2026-11-01'), (1, '2026-11-02'), (1, '2026-11-03'), (1, '2026-11-05'), (2, '2026-11-02'), (2, '2026-11-02'), (2, '2026-11-03');Window function questions
Find the second-highest salary in each department.
SELECT dept, name, salaryFROM ( SELECT dept, name, salary, DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk FROM employees) AS rankedWHERE rnk = 2;-- eng | Grace | 180-- eng | Linus | 180-- sales | Ken | 110The subquery is required, not a style choice. The PostgreSQL tutorial states that window functions are permitted only in the SELECT list and ORDER BY, not in WHERE, GROUP BY or HAVING, because they are computed after those clauses. Then explain why DENSE_RANK and not the others:
SELECT name, salary, ROW_NUMBER() OVER w AS row_num, RANK() OVER w AS rnk, DENSE_RANK() OVER w AS denseFROM employeesWHERE dept = 'eng'WINDOW w AS (ORDER BY salary DESC);-- Ada | 200 | 1 | 1 | 1-- Grace | 180 | 2 | 2 | 2-- Linus | 180 | 3 | 2 | 2-- Margaret | 150 | 4 | 4 | 3ROW_NUMBER breaks the tie arbitrarily, so Grace and Linus could swap between runs. RANK leaves a gap after ties, so nobody in engineering has rank 3. DENSE_RANK gives the “second distinct salary” most people mean. Ask which one the interviewer wants before writing the query, because “second highest” is ambiguous when there are ties.
Why does this running total jump on tied rows?
SELECT name, salary, SUM(salary) OVER (ORDER BY salary) AS default_frame, SUM(salary) OVER (ORDER BY salary, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_frameFROM employeesWHERE dept = 'eng'ORDER BY salary, id;-- Margaret | 150 | 150 | 150-- Grace | 180 | 510 | 330-- Linus | 180 | 510 | 510-- Ada | 200 | 710 | 710With ORDER BY, the default frame runs from the start of the partition through the current row plus its peers, rows with an equal sort value. PostgreSQL’s tutorial describes exactly that, and SQLite’s window function docs name the default as RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Grace and Linus are peers, so both get 510. A ROWS frame with a unique tiebreaker produces the row-by-row running total most people expect.
Compare each row with the previous one.
SELECT name, salary, salary - LAG(salary) OVER (ORDER BY salary, id) AS gap_from_previousFROM employeesWHERE dept = 'eng'ORDER BY salary, id;-- Margaret | 150 | NULL-- Grace | 180 | 30-- Linus | 180 | 0-- Ada | 200 | 20LAG reads a value from an earlier row in the window and LEAD from a later one; both return NULL when there is no such row unless you pass a default as the third argument. Month-over-month growth is the same pattern applied to a monthly aggregate: group by month in a CTE, then divide the difference by LAG(revenue), guarding against division by zero with NULLIF.
Join and NULL questions
WHERE or HAVING?
WHERE filters individual rows before grouping, so it can’t reference aggregates. HAVING filters groups after aggregation, so HAVING COUNT(*) > 1 works and WHERE COUNT(*) > 1 is an error. Put row-level conditions in WHERE even when you also have a HAVING: filtering early means less data to group.
UNION or UNION ALL?
UNION removes duplicate rows from the combined result, which costs a sort or hash step; UNION ALL keeps every row. Use UNION ALL unless you need deduplication, and say why when you choose UNION, because interviewers watch for the accidental performance cost.
Why did the LEFT JOIN drop employees with no orders?
SELECT COUNT(*) FROM employees eLEFT JOIN orders o ON o.employee_id = e.idWHERE o.status = 'paid'; -- 2 rows
SELECT COUNT(*) FROM employees eLEFT JOIN orders o ON o.employee_id = e.id AND o.status = 'paid'; -- 6 rows
SELECT e.name, COALESCE(SUM(o.amount), 0) AS paid_totalFROM employees eLEFT JOIN orders o ON o.employee_id = e.id AND o.status = 'paid'GROUP BY e.idORDER BY e.id;-- Ada 0, Grace 50, Linus 0, Margaret 0, Barbara 0, Ken 70The WHERE clause runs after the join. Employees without a paid order have NULL in o.status, the comparison is not true, and the rows disappear, turning the outer join into an inner join. Filters on the optional table belong in the ON clause.
Why does NOT IN return nothing here?
SELECT name FROM employeesWHERE id NOT IN (SELECT manager_id FROM employees);-- (no rows)
SELECT name FROM employees eWHERE NOT EXISTS (SELECT 1 FROM employees r WHERE r.manager_id = e.id);-- Grace, Linus, Margaret, KenThe manager_id column contains NULL. PostgreSQL’s subquery expression docs say that if there are no equal right-hand values and at least one right-hand row yields null, the result of NOT IN is null, not true. NOT EXISTS doesn’t have this problem, which is why it is the safer default for anti-joins.
COUNT(*), COUNT(column) or COUNT(DISTINCT column)?
SELECT COUNT(*) AS all_rows, COUNT(manager_id) AS with_manager, COUNT(DISTINCT manager_id) AS managersFROM employees;-- 6 | 4 | 2COUNT(*) counts rows, COUNT(column) skips NULLs, and COUNT(DISTINCT column) counts distinct non-null values. Most “wrong total” bugs in interviews come from mixing these up.
Pattern questions
Find each user’s login streaks (gaps and islands).
WITH days AS ( SELECT DISTINCT user_id, day FROM logins),grouped AS ( SELECT user_id, day, julianday(day) - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS grp FROM days)SELECT user_id, MIN(day) AS start_day, MAX(day) AS end_day, COUNT(*) AS streakFROM groupedGROUP BY user_id, grpORDER BY user_id, start_day;-- 1 | 2026-11-01 | 2026-11-03 | 3-- 1 | 2026-11-05 | 2026-11-05 | 1-- 2 | 2026-11-02 | 2026-11-03 | 2Consecutive dates minus consecutive row numbers give a constant, so each island shares a grp value. Deduplicate first, or the duplicate login on November 2 breaks the arithmetic. In PostgreSQL, with a date column, write day - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day))::int instead of the julianday expression.
Find duplicate rows.
SELECT user_id, day, COUNT(*) AS copiesFROM loginsGROUP BY user_id, dayHAVING COUNT(*) > 1;-- 2 | 2026-11-02 | 2To delete all but one copy, rank rows within each duplicate group with ROW_NUMBER() over a unique key and delete those numbered above 1. Then add a unique constraint so the duplicates can’t come back.
Performance and transaction questions
Which queries can use a composite index on (dept, salary)?
CREATE INDEX idx_emp_dept_salary ON employees (dept, salary);EXPLAIN QUERY PLAN SELECT name FROM employees WHERE dept = 'eng' AND salary > 160;-- SEARCH employees USING INDEX idx_emp_dept_salary (dept=? AND salary>?)EXPLAIN QUERY PLAN SELECT name FROM employees WHERE salary > 160;-- SCAN employeesEXPLAIN QUERY PLAN SELECT name FROM employees WHERE lower(dept) = 'eng';-- SCAN employeesPostgreSQL’s multicolumn index docs say a B-tree index can serve conditions on any subset of its columns but is most efficient with constraints on the leading columns. In SQLite’s query plan output, SEARCH means only a subset of rows is visited and SCAN means every row is read. Wrapping the column in a function also defeats the index unless you create an expression index on lower(dept). Our database indexing concept page covers the B-tree background.
A query got slow. How do you investigate?
Run EXPLAIN ANALYZE in PostgreSQL (or EXPLAIN QUERY PLAN in SQLite) and read it from the most expensive node. Look for full scans of large tables, row estimates far from the actual counts (stale statistics), and sorts or hashes spilling to disk. Then check the application side: an N+1 pattern that runs the same query once per row looks fine in a plan and terrible in production. Fix the biggest cost first and measure again.
Explain isolation levels.
| PostgreSQL level | Prevents | Still allows |
|---|---|---|
| Read Committed (default) | Dirty reads | Nonrepeatable reads, phantoms, anomalies |
| Repeatable Read | Also nonrepeatable reads and phantoms | Serialization anomalies |
| Serializable | All of these | Nothing, but may fail with 40001 |
PostgreSQL’s transaction isolation docs add three details worth saying: dirty reads are impossible at every level, because Read Uncommitted behaves like Read Committed; Repeatable Read prevents phantoms even though the SQL standard allows them there; and Serializable transactions can fail with SQLSTATE 40001, so the application must retry them.
Practice on data with ties and NULLs
Before any SQL round, rerun your favorite queries on a table with duplicate values, NULLs and an empty group, and say out loud what each should return. Recording those practice runs with ExtraBrain and reading the transcript helps you hear where you skipped the tie question. The data analyst mock interview page has more practice prompts, and our Python interview questions cover the scripting round that often follows. Use ExtraBrain during a real interview only if the employer’s rules allow it.
Sources (checked November 23, 2026)
- PostgreSQL 19 documentation, Window functions tutorial
- PostgreSQL 19 documentation, Subquery expressions
- PostgreSQL 19 documentation, Multicolumn indexes
- PostgreSQL 19 documentation, Transaction isolation
- SQLite, Window functions
- SQLite, EXPLAIN QUERY PLAN
FAQ
Which SQL dialect should I write in an interview?
Ask, then write standard SQL where you can. Window functions, CTEs and NOT EXISTS work the same way in PostgreSQL, MySQL 8, SQL Server and SQLite; date arithmetic is where dialects differ most.
Are CTEs slower than subqueries?
Usually not in modern databases, which can inline them. Use whichever reads more clearly, and check the plan if performance matters.
Should I normalize or denormalize?
Normalize transactional tables so each fact lives in one place and updates can’t drift apart. Denormalize deliberately for read-heavy analytics or hot paths, and name the cost: duplicated data that has to be kept in sync.
How do I handle “top N per group” in a database without window functions?
A correlated subquery that counts how many rows in the group have a higher value works, though slowly. Mention it as a fallback, then use window functions.