SQL interview questions and answers, from basic to advanced
SQL interview questions run from basics (joins, GROUP BY, NULL handling) through window functions and CTEs to senior topics such as indexing, query plans and transaction isolation. Most rounds ask you to write two to four queries in a shared editor while explaining your reasoning, then probe one query for edge cases and performance. Practice writing queries without autocomplete and saying what one row of each table represents before you join.
By Evin JohnPublished 11 min read
How SQL shows up in interviews
SQL is tested for analysts, data engineers, backend developers, database administrators and many product roles, and the emphasis changes with the job. Analyst and data roles get query writing on business tables. Backend and SQL developer interviews add schema design, indexes and transactions. DBA and senior data engineering loops go deep on execution plans, locking and replication. The same page covers all of it because the questions build on each other.
- Online test or screenTimed problems on a platform that runs your query against hidden data. Correct output on edge cases matters more than style here.
- Live query roundAn interviewer shares a schema (orders, users, events, employees) and asks for queries of rising difficulty. You are expected to talk through grain, joins and edge cases.
- Design and performanceFor developer and data engineering roles: model a small schema, choose indexes, read an EXPLAIN output, or fix a slow query.
- Scenario follow-upsWhat happens with duplicate rows, late data, a NULL in the join key, or ten times the volume.
Ask which database the interviewer has in mind. PostgreSQL, MySQL, SQL Server, Oracle, BigQuery and Snowflake differ on LIMIT versus TOP, date functions, string concatenation and median support. Saying "I will write PostgreSQL, tell me if you want another dialect" is a good opening.
Basic SQL interview questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| In what order does the database evaluate the clauses of a SELECT? | Logical query processing | FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT. This explains why a SELECT alias usually cannot be used in WHERE. |
| Inner join versus left join: which rows does each return? | Join semantics | Inner keeps only matches. Left keeps every left row and fills the right side with NULL when nothing matches. A filter on the right table in WHERE quietly turns a left join back into an inner one. |
| When do you use WHERE and when HAVING? | Row versus group filters | WHERE removes rows before aggregation and can use indexes; HAVING filters groups after aggregation, such as departments with more than ten people. |
| What does COUNT(*) count that COUNT(column) does not? | NULL handling in aggregates | COUNT(*) counts rows; COUNT(column) skips NULLs; COUNT(DISTINCT column) skips NULLs and repeats. |
| Primary key versus unique constraint? | Keys and integrity | One primary key per table, never NULL, usually the row identity. A table can have several unique constraints, and most engines allow NULLs in them (SQL Server allows only one). |
| What does a foreign key protect, and what does ON DELETE CASCADE change? | Referential integrity | Child rows cannot point at a missing parent. CASCADE deletes children with the parent, which is convenient and dangerous on large tables. |
| DELETE, TRUNCATE and DROP: what is the difference? | DML versus DDL | DELETE removes chosen rows and fires triggers. TRUNCATE empties the table quickly. DROP removes the table itself. Whether TRUNCATE can be rolled back depends on the engine. |
| UNION or UNION ALL? | Set operations and cost | UNION removes duplicates, which needs a sort or hash step. Use UNION ALL when duplicates are impossible or wanted. |
| CHAR versus VARCHAR? | Data types | CHAR is fixed length and padded; VARCHAR stores the actual length. Pick types for correctness first: money in DECIMAL, not FLOAT. |
| Explain first, second and third normal form in plain words. | Normalization | Atomic values, no column depending on only part of a composite key, no column depending on another non-key column. Then say when you would denormalize for reads. |
| What is a view, and how is a materialized view different? | Abstraction and caching | A view is a saved query run each time. A materialized view stores the result and must be refreshed, so it trades freshness for speed. |
| Correlated versus non-correlated subquery? | Subquery evaluation | A correlated subquery refers to the outer row, so logically it runs per row. Many optimizers rewrite it as a join, but you should be able to write the join yourself. |
The NULL question that catches people
Interviewers like to ask what this returns when the subquery contains a NULL. Comparisons with NULL are unknown, not false, so NOT IN against a list containing a NULL filters out every row. NOT EXISTS does not have this problem.
-- Returns nothing, because one manager_id is NULL
SELECT e.name
FROM employees e
WHERE e.id NOT IN (SELECT manager_id FROM employees);
-- Safe version: NULLs in the subquery do not matter
SELECT e.name
FROM employees e
WHERE NOT EXISTS (
SELECT 1 FROM employees r WHERE r.manager_id = e.id
);- How do you replace NULL with a default?
COALESCE(col, default)returns the first non-NULL argument and is standard. Mention thatNULL = NULLis not true, so joins on nullable keys drop those rows. - What is the result of SELECT 10 / 4? In PostgreSQL and SQL Server integer division gives 2; MySQL gives 2.5000. Cast one side to a decimal when you need a fraction, for example in a conversion rate.
- Can you ORDER BY a column that is not in the SELECT list? Usually yes, unless the query uses DISTINCT or the column is not grouped.
Intermediate SQL questions: queries you write live
These are the classic write-a-query prompts. For each, state the output grain first (one row per customer, per day, per department), then name the edge case you are handling.
- Find the second highest salary.
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees)works and returns NULL when there is no second value. For the Nth value, use DENSE_RANK so ties do not skip a level. - List customers who never ordered. A left join from customers to orders with
WHERE o.id IS NULL, or NOT EXISTS. Explain why an inner join cannot answer it. - Find duplicate emails, then delete all but the newest. GROUP BY on the normalized email with
HAVING COUNT(*) > 1to find them; ROW_NUMBER partitioned by email and ordered by created date to delete the rest. Ask whether case differences count as duplicates. - Show each customer's share of total revenue. Aggregate per customer, then divide by
SUM(SUM(amount)) OVER (). Nesting an aggregate inside a window function is legal and often surprises candidates. - Pivot monthly sales into one column per month. Conditional aggregation,
SUM(CASE WHEN month = 1 THEN amount END), works everywhere; PIVOT is SQL Server and Oracle syntax. - Compute month-over-month growth. Aggregate by month, then
LAG(revenue) OVER (ORDER BY month). Guard the division with NULLIF on the previous value. - Find orders placed within 24 hours of sign-up. A join with a time-window condition. Clarify time zones before writing the date math.
- Find employees who earn more than their manager. A self-join of employees to employees on manager_id.
- Return the first and the latest order per customer in one row. MIN and MAX of the date are easy; returning the whole first and last row needs ROW_NUMBER twice or FIRST_VALUE and LAST_VALUE with an explicit frame.
- Find the median order value. PostgreSQL has
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount). Without it, sort with ROW_NUMBER and COUNT and average the middle one or two rows.
WITH ranked AS (
SELECT dept, name, salary,
DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS pos
FROM employees
)
SELECT dept, name, salary
FROM ranked
WHERE pos <= 2
ORDER BY dept, salary DESC;| name | salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|---|
| Ana | 150 | 1 | 1 | 1 |
| Ben | 120 | 2 | 2 | 2 |
| Cy | 120 | 3 | 2 | 2 |
| Gus | 100 | 4 | 4 | 3 |
Be ready to say which one the business wants. "Top three products" with ROW_NUMBER silently drops a tied product, and the order between Ben and Cy is arbitrary unless you add a tiebreaker column to ORDER BY.
Advanced SQL questions: windows, CTEs and recursion
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Window function versus GROUP BY aggregate? | Window semantics | A window keeps every input row and adds a computed column; GROUP BY collapses rows. Windows are evaluated after WHERE and GROUP BY, so you cannot filter on them without a subquery or CTE (or QUALIFY in Snowflake and BigQuery). |
| Why does a running total jump on days with two orders? | Default window frame | With ORDER BY and no frame, most engines default to RANGE, which includes all peer rows with the same sort value. Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW plus a unique tiebreaker. |
| Write a seven-day moving average. | Frames | AVG(x) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), and note that it assumes one row per day; fill missing days from a calendar table first. |
| CTE or subquery or temp table? | Readability and execution | CTEs make steps readable. Some engines inline them, others may materialize them. A temp table helps when an intermediate result is reused and benefits from its own index. |
| Walk an org chart from one employee to the CEO. | Recursive CTEs | An anchor row, a recursive member joined on manager_id, and a depth column. Mention a depth cap or cycle check for bad data. |
| Find each user's streaks of consecutive login days. | Gaps and islands | Subtract a row number from the date: consecutive days give the same group value. Deduplicate days first. |
| Calculate week-one retention by sign-up cohort. | Cohorts and date logic | Define retained in words first, build the cohort table, left join activity in the window, and divide with a decimal cast. |
| Find overlapping bookings for the same room. | Interval logic | Two ranges overlap when each starts before the other ends: a.start_at < b.end_at AND b.start_at < a.end_at, with a.id < b.id to avoid pairing a row with itself. |
WITH days AS (
SELECT DISTINCT user_id, login_date FROM logins
),
numbered AS (
SELECT user_id, login_date,
login_date - CAST(ROW_NUMBER() OVER (
PARTITION BY user_id ORDER BY login_date) AS int) AS grp
FROM days
)
SELECT user_id,
MIN(login_date) AS streak_start,
MAX(login_date) AS streak_end,
COUNT(*) AS streak_days
FROM numbered
GROUP BY user_id, grp
ORDER BY user_id, streak_start;WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE id = 7
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e
JOIN chain c ON e.id = c.manager_id
WHERE c.depth < 20
)
SELECT name, depth FROM chain ORDER BY depth;Senior SQL questions: indexes, plans and transactions
- How does a B-tree index speed up a query, and what does it cost? It turns a scan into a seek on sorted keys. Every insert, update and delete must maintain it, and it uses storage and memory.
- You have an index on (customer_id, created_at). Which filters can use it? Equality on customer_id, and customer_id plus a range on created_at. A filter on created_at alone usually cannot seek on it, because the leading column is missing.
- What makes a predicate non-sargable? Wrapping the indexed column in a function or expression, such as
WHERE YEAR(created_at) = 2025orWHERE amount * 1.1 > 100. Rewrite as a range on the bare column, or add an expression index where the engine supports one. - Clustered versus nonclustered index? A clustered index stores the table rows in key order, so there is at most one. In SQL Server it is a choice; in MySQL InnoDB the primary key is the clustered index. PostgreSQL tables are heaps and every index is secondary.
- What is a covering index? An index that holds every column the query needs, so the engine can answer from the index without visiting the table (INCLUDE columns in SQL Server and PostgreSQL).
- How do you read an execution plan? Find the step with the most actual time or rows, compare estimated with actual row counts, and look for sequential scans on large tables, nested loops over many rows, and sorts that spill to disk. In PostgreSQL use
EXPLAIN (ANALYZE, BUFFERS), carefully on writes because ANALYZE executes the statement. - Why would the optimizer ignore your index? The filter matches a large share of the table, statistics are stale, the predicate is non-sargable, types do not match and force a cast, or the index column order does not fit.
- Explain ACID with one example per letter. Atomic transfer of money between accounts, constraints holding after commit, concurrent transactions not seeing each other's partial work, and committed data surviving a crash because the log was flushed.
- Name the isolation levels and the anomaly each prevents. Read uncommitted, read committed (no dirty reads), repeatable read (no non-repeatable reads), serializable (no phantoms or write skew). Defaults differ: PostgreSQL and SQL Server use read committed, MySQL InnoDB uses repeatable read.
- What causes a deadlock and how do you prevent it? Two transactions locking the same rows in opposite order. Lock in a consistent order, keep transactions short, index the columns used to find rows, and retry the victim.
- Optimistic versus pessimistic locking? A version column checked on update, versus
SELECT ... FOR UPDATE. Optimistic suits low-conflict edits; pessimistic suits hot rows such as inventory counts. - When do you partition a table? When queries and retention follow a key such as month, so the engine prunes partitions and old data is dropped by detaching a partition rather than a huge DELETE.
- How would you change a column type on a busy table without downtime? Add a new column, backfill in batches, dual-write from the application, switch reads, then drop the old column. Avoid long table locks.
- OLTP versus OLAP? Many small transactions on normalized row stores, versus large scans and aggregations on columnar, often denormalized data such as star schemas.
- When is SQL the wrong store? Bring trade-offs, not slogans; the comparison in SQL vs NoSQL for system design is a good base, and database sharding covers splitting a relational database across machines.
Scenario and debugging questions
| Scenario | Likely cause | What to say you would check |
|---|---|---|
| A revenue report doubled after someone added a payments join. | Join fan-out | One order has two payment rows, so the order amount is counted twice. Aggregate payments per order before joining, or join at the right grain. |
| A query that took one second now takes a minute. | Plan change | Data growth, stale statistics or a new parameter value. Compare plans, refresh statistics, check for a missing index after a schema change. |
| Yesterday's daily total is wrong only for users in Asia. | Time zones | Timestamps stored in UTC but the day boundary cut in local time, or the reverse. Store UTC, convert once at the edge. |
| Two checkout requests sold the last item twice. | Race condition | Read then write without a lock or condition. Use an atomic UPDATE ... SET stock = stock - 1 WHERE stock > 0 and check the affected row count. |
| A nightly delete job blocks the application. | Long transaction and lock escalation | Delete in small batches by key, commit between batches, or partition by date and drop old partitions. |
| A LEFT JOIN returns fewer rows than the left table. | Filter in WHERE | A condition on the right table in WHERE removes the NULL rows. Move it into the ON clause. |
Fictional example
- Interviewer
- The orders dashboard used to load in two seconds and now takes forty. Walk me through it.
- Candidate
- First I would get the actual plan with EXPLAIN ANALYZE on a copy, not guess. Say it shows a sequential scan on orders with a filter on
DATE(created_at) = CURRENT_DATE. Wrapping the column in DATE stops the index on created_at from being used, and the table has grown enough that the scan hurts. I would rewrite it as a range,created_at >= CURRENT_DATE AND created_at < CURRENT_DATE + 1, and confirm the plan switches to an index scan. If the query also groups by store, I would check whether a composite index on (store_id, created_at) serves both. Then I would check the estimated versus actual rows, because a large gap means stale statistics, and I would add the query to monitoring so the next regression is caught before a user reports it.
A three-week SQL practice plan
- Week 1, foundations: joins, GROUP BY with HAVING, NULL behavior and subqueries. Write ten queries on a sample orders schema by hand, then run them and compare with what you predicted.
- Week 2, windows and CTEs: ROW_NUMBER, RANK, DENSE_RANK, LAG and LEAD, running totals with explicit frames, a recursive CTE and one gaps-and-islands problem. Predict each output before running it.
- Week 3, performance: create a table with a few million generated rows, run EXPLAIN before and after adding indexes, break sargability on purpose, and practice explaining isolation levels and a deadlock out loud.
- Every day: say the grain of each table and the edge cases (ties, NULLs, duplicates, empty groups) before writing. That habit is what separates a correct answer from a lucky one.
For related role guides, see data analyst interview questions for business cases and data engineer interview questions for pipelines and modeling. Backend developers who meet SQL inside an API service can continue with Node.js interview questions.
When you rehearse, the gap is usually in the explaining, not the query. Natively, an AI interview assistant for Mac and Windows, transcribes a mock SQL round on your computer so you can reread where you skipped the grain or forgot the NULL case. During practice it can read a query prompt from a screenshot and suggest an approach, and with Pro or the free trial it can tailor suggestions to the résumé and job description you add. The transcript and notes stay available for review afterwards.
Questions people ask
What SQL questions are asked in interviews?
Expect joins, GROUP BY with HAVING, NULL handling and subqueries first, then window functions such as ROW_NUMBER, RANK and LAG, CTEs, deduplication and top N per group. Senior rounds add indexes, execution plans, transactions and isolation levels.
How do I prepare for an advanced SQL interview?
Practice window functions with explicit frames, recursive CTEs and gaps-and-islands problems, then read EXPLAIN output on a table large enough for indexes to matter. Say the grain of each table and the edge cases before you write.
What is the difference between RANK, DENSE_RANK and ROW_NUMBER?
ROW_NUMBER gives every row a unique number even on ties. RANK gives tied rows the same number and skips the next ones. DENSE_RANK gives ties the same number without gaps.
Are SQL developer interview questions different from data analyst ones?
The query questions overlap. SQL developer and backend interviews add schema design, indexes, stored procedures, transactions and locking, while analyst rounds lean toward business metrics and cohort queries.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
