SQL Interview Questions 2026: 38 Questions With Answers
SQL interview questions in 2026 fall into three buckets: concept recall (joins, normalization, ACID), query writing (the live coding round where you type SQL while someone watches), and optimization reasoning (why is this query slow, how would you index it). The new-grad gap is that you can read SQL fine but freeze when asked to write a window function or explain an execution plan out loud. This guide gives 45+ questions across all three, with answer outlines you can say in your own voice.
By Sam K., Founder, InterviewChamp.AI · Last updated
26 min readTL;DR: The SQL questions you'll hear most are second-highest salary, top N rows per group, running totals, duplicate rows, INNER JOIN versus LEFT JOIN, and why a slow query is slow. Nearly every round mixes a few concept questions with at least one live query you write while someone watches, and that live part is what sinks new grads. Below are 38 questions with answers, sorted by topic, plus the six coding patterns and a two-week plan to get them into your fingers.
What are the most common SQL interview questions in 2026?#
The short list is in the TL;DR above, and every one of those prompts gets a full answer below. What ties them together is simple. Nobody grades you on recognizing correct SQL. They grade you on producing working SQL against a schema you've never seen, out loud, in about five minutes, while you explain what you're doing. This guide sorts the material into the buckets interviewers test, gives you a question bank for each one, and walks through the small set of coding patterns that cover most of what gets asked.
What SQL interviews test in 2026#
Three separate skills get tested, and most candidates over-prepare the first one.
- Concept recall: can you explain join types, normalization, indexing and ACID without reading off a slide?
- Query writing: can you sit down at a blank editor and produce a correct query for a schema you've never seen before?
- Optimization reasoning: can you look at a slow query or an execution plan and say what's wrong and how you'd fix it?
Here's a rough split from experience of how a typical new-grad SQL round divides its time (treat it as a guide, not measured data):
| Skill | Share of the round | What it covers |
|---|---|---|
| Concept recall | 30-40% | joins, normalization, ACID, WHERE vs HAVING |
| Live query writing | 40-50% | the coding round on a shared screen, or a take-home |
| Optimization reasoning | 15-25% | slow query diagnosis, index choices, reading a plan |
That split moves a lot depending on the role. A data analyst loop is mostly query writing with a little optimization. A data engineer or backend engineer loop pushes optimization to 30% or more, since those people own the queries that run in production at scale. A general software engineer loop often treats SQL as one slice of a bigger technical round: the fundamentals, plus one or two queries.
The 2026 hiring environment rewards whoever can write SQL live. Take-home assessments and proctored remote screens are still common. But the live shared-screen round has become the default filter at most mid-market and large employers, because it's the cheapest way to find out whether "proficient in SQL" on a resume is real. Picture a candidate who can recite how a clustered index differs from a non-clustered one, then freezes when asked for a top-3-per-category query. That person reads as someone who studied for the interview without ever doing the reps.
The question list at a glance#
Use this as a map. Every question below has a full answer further down, and the numbers match.
| Topic | Questions | What you should walk away able to do |
|---|---|---|
| Joins | Q1 to Q8 | pick the right join and spot the LEFT JOIN filter trap |
| Indexing | Q9 to Q14 | explain the read and write trade-off and the leftmost-prefix rule |
| Normalization | Q15 to Q19 | define 1NF to 3NF and say when to break the rules |
| Aggregation | Q20 to Q24 | keep WHERE and HAVING straight and handle NULLs in totals |
| Subqueries and CTEs | Q25 to Q28 | choose between them and write a recursive CTE |
| Window functions | Q29 to Q34 | write top N per group and a running total without notes |
| Transactions and ACID | Q35 to Q38 | explain isolation levels, read anomalies and deadlocks |
If you're short on time, start with the window function section and the live coding round. That's where most rounds get decided.
Key terms#
Think of the vocabulary below as the floor. If any of it feels fuzzy, your concept answers will wobble, and your live queries will slow down because you're thinking about mechanics instead of the actual problem.
Join: an operation that combines rows from two or more tables on a related column, giving one result set that pulls columns from each table.
Index: a separate data structure (usually a B-tree) that lets the database find matching rows without scanning the whole table. You pay for it with extra storage and slower writes, and you get faster reads back.
Normalization: arranging tables so redundant data goes away and update anomalies can't happen, described as a series of normal forms (1NF, 2NF, 3NF, and beyond).
Transaction: a unit of work holding one or more statements that either all commit together or all roll back together, which is what gives you the ACID guarantees.
Window function: a function that computes a value across a set of related rows, defined by an OVER clause, without squashing those rows into one the way an aggregate with GROUP BY does.
Execution plan: the step-by-step strategy the query planner picks to run a query. It shows whether it uses an index seek or a full table scan, which join algorithm it chose, and how many rows it expects at each step.
Three more come up in answers all the time. A primary key is the column (or set of columns) that uniquely identifies each row, and it can't be NULL. A foreign key is a column pointing at another table's primary key, which enforces referential integrity: you can't insert an order that points at a customer with no row. Cardinality is the number of distinct values in a column, and it drives index decisions. A high-cardinality column like an email address makes a good index candidate. A low-cardinality one like a boolean flag usually doesn't.
SQL join interview questions (8 Q)#
Joins get tested more than any other concept, because every non-trivial query is built on them. These eight cover the join types and the traps interviewers like to set.
What are the different types of joins?
Show sample answerHide answerSay yours out loud first, then check.
INNER JOIN returns only rows that have a match in both tables. LEFT JOIN returns every row from the left table plus any matches from the right, with NULLs filling in where there's no match. RIGHT JOIN is just the mirror image. FULL OUTER JOIN gives you all rows from both tables, matched where possible and NULL-filled where not. CROSS JOIN returns the Cartesian product: every row of A paired with every row of B.
What the interviewer wants to hear is whether you know a LEFT JOIN is the right tool when you want to keep rows without a match, like customers who placed zero orders.
What is the difference between INNER JOIN and LEFT JOIN?
Show sample answerHide answerSay yours out loud first, then check.
INNER JOIN keeps only matched rows. LEFT JOIN holds on to all left-table rows, whether they match or not.
Now the trap interviewers love. Say you filter a LEFT JOIN on a right-table column inside the WHERE clause. The NULL rows that came from unmatched left records fail that condition and vanish, which quietly turns your LEFT JOIN into an INNER JOIN. To hold on to the unmatched rows, move the right-table condition into the ON clause:
-- Wrong: this drops customers with no 2026 orders
SELECT c.name, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.order_year = 2026;
-- Right: keeps every customer, NULL total if no 2026 order
SELECT c.name, o.total
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.id AND o.order_year = 2026;
What is a self-join and when do you use one?
Show sample answerHide answerSay yours out loud first, then check.
A self-join joins a table to itself, normally with two table aliases. You reach for it when you need to compare rows inside the same table. The classic one is finding employees who earn more than their manager, by joining employees to employees on manager_id. Comparing this month's row to last month's is another.
The point worth making in the interview: there's nothing special about the mechanics. It's the same table showing up twice under two names. Here's the manager version:
-- Staff paid more than the person they report to
SELECT worker.name, boss.name AS boss_name, worker.salary
FROM employees AS worker
INNER JOIN employees AS boss
ON boss.id = worker.manager_id
WHERE worker.salary > boss.salary;
What is a cross join and when is it dangerous?
Show sample answerHide answerSay yours out loud first, then check.
A CROSS JOIN produces the Cartesian product, so every row of the first table gets paired with every row of the second. Cross a 1,000-row table with another 1,000-row table and you get 1,000,000 rows.
The real danger is the accidental cross join, which happens when you forget the join condition. Two tables of a few hundred thousand rows each, plus a missing ON clause, can produce billions of rows and lock up the database. Some interviewers will show you a query that's missing its join predicate just to see if you catch it.
What is the difference between a join and a subquery?
Show sample answerHide answerSay yours out loud first, then check.
A join combines columns from several tables into one result set. A subquery is a query nested inside another one, sitting in a WHERE, FROM or SELECT clause, usually to compute a value or build a filter set. Plenty of problems can be solved either way.
The nuance that matters: correlated subqueries, the kind that reference the outer query and run once per outer row, can get slow on large tables. Rewriting one as a join often speeds things up. (Q28 goes deeper on that.)
How do you find rows in table A that have no match in table B?
Show sample answerHide answerSay yours out loud first, then check.
That's the anti-join, and you'll see it constantly. The clean way is a LEFT JOIN with a NULL check, or NOT EXISTS:
-- Customers who have never placed an order
SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;
NOT IN works too, but it breaks in a sneaky way if the subquery returns even one NULL. So NOT EXISTS or the LEFT JOIN NULL check is the safer answer to give out loud.
What does a FULL OUTER JOIN return and when would you use it?
Show sample answerHide answerSay yours out loud first, then check.
Every row from both tables: matched where the join condition holds, NULL-filled on whichever side has no match. The realistic use is reconciliation. You've got two datasets that should line up, say a list of expected payments and a list of received payments, and you want the unmatched expected rows and the unmatched received rows together in one result.
What is the difference between UNION and UNION ALL?
Show sample answerHide answerSay yours out loud first, then check.
Both stack two result sets on top of each other, and the columns have to match in count and type. UNION removes duplicate rows, which forces a sort or hash step and costs time. UNION ALL keeps everything, duplicates included, and runs faster.
A good answer reaches for UNION ALL by default and only uses UNION when you need duplicates gone, since that deduplication isn't free.
SQL indexing interview questions (6 Q)#
Indexing is where query writing runs into optimization. Backend and data-engineer loops lean hard on it. Analyst loops just touch it.
What is an index and how does it work?
Show sample answerHide answerSay yours out loud first, then check.
An index is a separate data structure, usually a B-tree, that keeps the indexed column's values in sorted order with pointers back to the table rows. Instead of scanning every row looking for a match, the database walks down the B-tree, which is a logarithmic-time lookup rather than a linear scan.
The cost shows up on writes. Every insert, update or delete has to maintain the index too, and the index takes extra storage.
When does an index help and when does it hurt?
Show sample answerHide answerSay yours out loud first, then check.
It helps reads that filter or join on the indexed column, especially equality and range lookups on big tables. It hurts in three situations:
- Write-heavy tables, where the maintenance cost outweighs what you gain on reads.
- Low-cardinality columns like a boolean, where the index barely narrows anything down.
- Small tables, where a full scan is already cheap.
The senior answer names the trade-off directly: indexes speed up reads and slow down writes, so you add them on purpose, not by default.
What is the difference between a clustered and a non-clustered index?
Show sample answerHide answerSay yours out loud first, then check.
A clustered index decides the physical order of rows in the table, so you only get one per table (the primary key is usually the clustered one). You can have many non-clustered indexes, and each one lives apart from the table and points back to its rows.
Why it matters: a lookup on the clustered index is fast because the data is sitting right there in order, while a non-clustered lookup may need an extra hop to fetch the full row.
Name the database when you answer. This is how SQL Server and MySQL's InnoDB work, but PostgreSQL has no maintained clustered index. Its CLUSTER command reorders a table once, and later inserts and updates are not kept in that order.
What is a composite index and does column order matter?
Show sample answerHide answerSay yours out loud first, then check.
A composite index covers more than one column, and yes, order matters a great deal. An index on (last_name, first_name) speeds up queries that filter on last_name alone or on both columns. It doesn't help a query that filters only on first_name, because the index is sorted by last_name first.
That's the leftmost-prefix rule. It's a favorite follow-up, too: interviewers will hand you a composite index and ask which queries it can serve.
Why might a query with a matching index still do a full table scan?
Show sample answerHide answerSay yours out loud first, then check.
The usual culprit is a function wrapped around the indexed column, which blocks the index. WHERE YEAR(created_at) = 2026 can't use an index on created_at, because the database has to compute YEAR() for every single row. Rewrite it as a range instead:
-- Blocks the index on created_at
WHERE YEAR(created_at) = 2026;
-- Uses the index: a sargable range predicate
WHERE created_at >= '2026-01-01'
AND created_at < '2027-01-01';
Two other causes are worth naming. The planner may estimate that the query returns most of the table, and then a scan is in fact cheaper than lots of index lookups. Or the statistics are stale.
What is a covering index?
Show sample answerHide answerSay yours out loud first, then check.
A covering index holds every column a query touches. The database then answers straight from the index and never goes back to the table. If a query selects customer_id and total and filters on customer_id, an index on (customer_id, total) covers it.
You win by skipping the row lookups completely. You pay with a wider index that takes more space and more write maintenance.
SQL normalization interview questions (5 Q)#
Normalization questions show whether you understand schema design and not just query syntax. They come up a lot in data-platform and backend rounds.
What is normalization?
Show sample answerHide answerSay yours out loud first, then check.
It's how you organize tables to cut redundancy and avoid anomalies when you insert, update or delete data. The goal is for each fact to live in exactly one place, so changing it never means touching several rows. It's described in normal forms, each one stricter than the last.
Explain 1NF, 2NF, and 3NF.
Show sample answerHide answerSay yours out loud first, then check.
First normal form: every column holds one atomic value. No repeating groups, no comma-separated lists stuffed into a cell.
Second normal form: the table is already in 1NF, and every non-key column depends on the whole primary key, not just part of a composite key.
Third normal form: the table is already in 2NF, and no non-key column depends on another non-key column (so no transitive dependencies).
A tidy way to say it in the room: "every non-key column depends on the key, the whole key, and nothing but the key."
What is denormalization and why would you do it on purpose?
Show sample answerHide answerSay yours out loud first, then check.
Denormalization means deliberately putting redundancy back into a schema so reads go faster. Read-heavy analytics and reporting systems do this so a dashboard query doesn't have to join six tables every time it loads.
The catch is that you now have to keep that redundant data consistent, usually through application logic or scheduled jobs. The mature answer treats normalization and denormalization as tools for different access patterns rather than a right-or-wrong choice.
What problems does normalization prevent?
Show sample answerHide answerSay yours out loud first, then check.
Three classic anomalies:
- Update anomaly: one fact is stored in many rows, so an update has to hit all of them, and missing one leaves the data inconsistent.
- Insertion anomaly: you can't record a new fact because the row also demands other, unrelated data you don't have.
- Deletion anomaly: deleting one row wipes out a fact you wanted to keep.
Naming all three is the signal that you get why normalization exists, instead of treating it as a rule you memorized.
When is a fully normalized schema the wrong choice?
Show sample answerHide answerSay yours out loud first, then check.
When the workload is read-heavy and join cost dominates, as in analytics warehouses and reporting layers. Star and snowflake schemas in data warehousing denormalize dimensions on purpose to keep queries quick.
In a backend interview, the right answer is rarely "always go to the highest normal form." It's closer to "normalize the transactional system, then denormalize selectively for the read paths that need it."
SQL aggregation interview questions: GROUP BY and HAVING (5 Q)#
These questions check whether you understand the order SQL evaluates a query in. That's exactly where the WHERE versus HAVING mix-up comes from.
What is the difference between WHERE and HAVING?
Show sample answerHide answerSay yours out loud first, then check.
WHERE filters individual rows before grouping happens. HAVING filters groups after GROUP BY has aggregated them. You can't put an aggregate like COUNT() or SUM() in WHERE, because at that stage nothing has been aggregated yet. "Find customers with more than five orders" needs the count in HAVING:
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 5;
In what order does SQL logically evaluate a query?
Show sample answerHide answerSay yours out loud first, then check.
The logical order runs: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, then LIMIT.
That sequence explains two things interviewers poke at. You can't reference a SELECT alias in the WHERE clause, because WHERE runs before SELECT. And aggregates go in HAVING, not WHERE, because HAVING runs after grouping. Once this order is in your head, a whole family of "why does this throw an error" questions answers itself.
What does COUNT(*) count versus COUNT(column)?
Show sample answerHide answerSay yours out loud first, then check.
COUNT(*) counts every row in the group, including rows where columns are NULL. COUNT(column) only counts rows where that particular column isn't NULL.
It's a common trap. Run COUNT(email) on a table where some emails are NULL and you'll get a smaller number than COUNT(*), and mixing the two up gives you wrong analytics.
How do NULLs behave in aggregate functions?
Show sample answerHide answerSay yours out loud first, then check.
Aggregates skip NULLs. SUM, AVG, MIN and MAX ignore NULL values entirely, and AVG divides by the count of non-NULL rows, not the total row count. So the average of [10, 20, NULL] is 15, not 10, because the NULL is left out of both the sum and the divisor.
The related trap: SUM over zero rows returns NULL, not 0, as the PostgreSQL aggregate function docs point out. Wrap it in COALESCE(SUM(x), 0) when whoever calls the query expects a number. Saying this out loud shows you understand NULL semantics, which are behind a lot of the most subtle SQL bugs.
Can you filter on an aggregate without a GROUP BY?
Show sample answerHide answerSay yours out loud first, then check.
Yes. HAVING works on a query with no GROUP BY because it treats the full result as a single group. SELECT COUNT(*) FROM orders HAVING COUNT(*) > 100 returns the count only when there are more than 100 orders.
You won't write this often in real work. Still, it's a fair test of whether you understand that HAVING operates on groups, and that a query without GROUP BY is just one implicit group.
SQL subqueries vs CTEs interview questions (4 Q)#
This pairing is a 2026 favorite, because CTEs plus window functions are how modern SQL gets written.
What is a CTE and how is it different from a subquery?
Show sample answerHide answerSay yours out loud first, then check.
A CTE (common table expression) is a named, temporary result set you define with a WITH clause at the top of a query and then reference by name in the main query. A subquery is an unnamed query nested inline.
They overlap a lot. The differences worth saying in an interview: a CTE can be referenced more than once in the same query, it reads top to bottom (much easier to follow when the logic gets complicated), and it supports recursion, which subqueries don't.
When should you prefer a CTE?
Show sample answerHide answerSay yours out loud first, then check.
Go with a CTE when the same derived set gets used more than once, when nesting would otherwise run three or more levels deep, or when you need recursion, like walking an org chart or a category tree. Stick with a plain inline subquery for one simple filter, where giving it a name adds ceremony and no clarity.
In most modern engines the planner optimizes both in a similar way. So the choice comes down to readability far more often than raw speed.
What is a recursive CTE and what is it for?
Show sample answerHide answerSay yours out loud first, then check.
A recursive CTE refers to itself so it can walk hierarchical or graph-shaped data. The standard example is an org chart: start with the CEO, then keep joining to find direct reports until you hit the leaves.
The structure is an anchor member (the starting rows), then UNION ALL, then a recursive member (the rows that join back to the CTE). In PostgreSQL you write it as WITH RECURSIVE, which, in the words of the PostgreSQL docs on WITH queries, lets a WITH query refer to its own output. Here's the org chart version:
-- The whole org chart, starting from anyone with no manager (level 1)
WITH RECURSIVE chain AS (
-- anchor: the person with no manager
SELECT top_boss.id, top_boss.name, 1 AS level
FROM employees AS top_boss
WHERE top_boss.manager_id IS NULL
UNION ALL
-- recursive step: people who report to someone already found
SELECT staff.id, staff.name, chain.level + 1
FROM employees AS staff
INNER JOIN chain ON staff.manager_id = chain.id
)
SELECT level, name
FROM chain
ORDER BY level, name;
Interviewers ask this one to separate people who've only written flat queries from people who've dealt with tree-shaped data.
What is a correlated subquery and why can it be slow?
Show sample answerHide answerSay yours out loud first, then check.
A correlated subquery references a column from the outer query, so it has to run once for every row the outer query produces. On a big outer table, that can mean millions of executions.
The fix is often a rewrite as a join or a window function, which the planner can run in a single pass. Spotting the correlation and knowing the rewrite is the optimization signal interviewers are looking for.
SQL window function interview questions (6 Q)#
If you only have time for one section, make it this one. Top-N-per-group and running-total questions show up in most live coding rounds, and both need window functions.
What is a window function and how is it different from GROUP BY?
Show sample answerHide answerSay yours out loud first, then check.
A window function computes a value across a set of related rows but doesn't collapse them. GROUP BY shrinks each group down to one row. A window function keeps every row and adds the computed column next to it.
You define the window with OVER, optionally with PARTITION BY to reset per group and ORDER BY to set the order inside the window. That's the core distinction they want to hear: the same aggregation power, with row-level output kept. The PostgreSQL window functions tutorial is the clearest short reference to rehearse from.
What is the difference between ROW_NUMBER, RANK, and DENSE_RANK?
Show sample answerHide answerSay yours out loud first, then check.
All three number the rows inside an ordered window. They only differ on ties:
| Function | Ties | Two rows tied for first, then the next row |
|---|---|---|
ROW_NUMBER | never ties, every row gets a unique number | 1, 2, 3 |
RANK | tied rows share a number, then it skips | 1, 1, 3 |
DENSE_RANK | tied rows share a number, no skip | 1, 1, 2 |
The practical choice: use ROW_NUMBER when you need exactly one row per group (like the single latest order), and RANK or DENSE_RANK when ties should share a position.
How do you get the top N rows per group?
Show sample answerHide answerSay yours out loud first, then check.
This is the most common live SQL coding question there is. Number the rows inside each partition with a window function, then filter:
-- Top 3 best-selling products per category
SELECT category, product, revenue
FROM (
SELECT category, product, revenue,
ROW_NUMBER() OVER (
PARTITION BY category
ORDER BY revenue DESC
) AS rn
FROM product_sales
) ranked
WHERE rn <= 3;
In standard SQL you can't filter on the window function in the same SELECT, since it's computed after WHERE. So you wrap it in a subquery or CTE and filter on the alias. Some warehouses give you a shortcut: Snowflake's QUALIFY clause filters window-function results directly, but Snowflake notes it is not part of the ANSI standard. Write the portable version unless the interviewer names the warehouse.
Knowing about that wrapping step is the detail that separates people who've written this query from people who've only read about it.
How do you calculate a running total?
Show sample answerHide answerSay yours out loud first, then check.
Use SUM over a window ordered by whatever you're running across:
SELECT order_date, amount,
SUM(amount) OVER (
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM orders;
The ROWS BETWEEN frame is the precise bit. Leave the frame out, and the default frame in many engines also counts every tied row with an equal ORDER BY value, which can give you a result you didn't mean. Spelling the frame out is the senior move.
What do LAG and LEAD do?
Show sample answerHide answerSay yours out loud first, then check.
LAG returns a value from an earlier row in the window. LEAD returns one from a later row. They let you compare a row with its neighbor without a self-join: month-over-month growth, the gap between two consecutive logins, the change from the previous reading.
LAG(amount, 1) gives you the previous row's amount, and subtracting it from the current row gives you the delta. Reaching for LAG or LEAD instead of a self-join tells the interviewer you're fluent in modern SQL.
What is the difference between PARTITION BY and GROUP BY?
Show sample answerHide answerSay yours out loud first, then check.
GROUP BY collapses each group into one output row. PARTITION BY, inside a window function's OVER clause, defines the group the window works over but keeps every row.
So AVG(salary) OVER (PARTITION BY department) shows every employee next to their department's average salary on the same row. GROUP BY department would hand back one row per department instead. Same grouping idea, different shape of output.
SQL transaction and ACID interview questions (4 Q)#
Transaction questions check whether you understand correctness when lots of things happen at once. That matters most in backend and platform roles.
What is ACID?
Show sample answerHide answerSay yours out loud first, then check.
Four guarantees:
- Atomicity: every statement in a transaction commits together or rolls back together.
- Consistency: a transaction moves the database from one valid state to another and respects every constraint.
- Isolation: concurrent transactions don't step on each other, and the isolation level decides how strictly.
- Durability: once something is committed, it survives a crash or a power loss.
The textbook example is a money transfer. Atomicity is what guarantees you never debit one account without crediting the other.
What are the SQL isolation levels?
Show sample answerHide answerSay yours out loud first, then check.
There are four standard levels. From weakest to strongest:
- Read Uncommitted: can read changes that haven't been committed, which allows dirty reads.
- Read Committed: only reads committed data.
- Repeatable Read: the same query returns the same rows inside one transaction.
- Serializable: transactions behave as if they ran one at a time.
Higher isolation blocks more anomalies but cuts concurrency. PostgreSQL, SQL Server and Oracle default to Read Committed (MySQL InnoDB defaults to Repeatable Read), and teams usually step up only for code paths that need stronger guarantees.
What are dirty reads, non-repeatable reads, and phantom reads?
Show sample answerHide answerSay yours out loud first, then check.
A dirty read is reading data another transaction wrote but hasn't committed yet, and might still roll back. A non-repeatable read is reading the same row twice inside one transaction and getting a different value, because another transaction committed a change in between. A phantom read is re-running a range query and seeing new rows that another transaction inserted.
Each isolation level blocks a bigger set of these. Read Committed stops dirty reads. Repeatable Read also stops non-repeatable reads. Serializable stops phantoms as well.
What is a deadlock and how do you prevent it?
Show sample answerHide answerSay yours out loud first, then check.
A deadlock is when two transactions each hold a lock the other one needs, so neither can move. The database notices and kills one of them so the other can finish.
To prevent it:
- Take locks in the same order across every code path.
- Keep transactions short so locks are held briefly.
- Use the lowest isolation level that's still correct for the job.
The practical detail interviewers want: the database settles a deadlock by aborting a victim transaction, and your application has to be ready to retry it.
The live SQL coding round#
Most SQL interviews get decided here, and it's the format new grads rehearse the least. You get a schema, often two to four tables, and you write a query on a shared screen or in a collaborative editor while the interviewer watches and listens. Reading correct SQL is easy. Producing it while being watched, and narrating as you go, uses a completely different muscle.
What the round grades, in order
- Do you ask clarifying questions first? Before you write anything, confirm the schema. Which table holds the foreign key? Can the left side have zero matches? Should NULLs be counted? Is there a tie-break rule for "the latest" row? Two or three good questions buy you thinking time, and they show you know requirements shape the query.
- Do you narrate your approach before typing? Say the plan out loud: "I'll join orders to customers, group by customer, then filter with HAVING." Interviewers grade reasoning, and a silent candidate who types a correct query still scores lower than one who explains it.
- Can you write it correctly, one piece at a time? Strong candidates build it up. Get the join working and run it. Add the grouping and run it. Add the filter. They don't write 30 lines and hope. Building in small steps is how you catch your own mistakes live.
- Can you reason about correctness and edge cases? Once it runs, say what could break: "this assumes every order has a valid customer_id; if there are orphaned orders, I'd switch to a LEFT JOIN." That unprompted edge-case thinking is the senior signal, even at entry level.
The six prompts to drill
The recurring prompts are a small set. Drill these six until you can write each one cold, both with a window function and with a plain subquery, because some interviewers ban window functions to make you prove you understand the mechanics:
| Prompt | First-choice approach | Fallback if window functions are banned |
|---|---|---|
| Second-highest salary | DENSE_RANK() then filter = 2 | Distinct salaries sorted high to low, then LIMIT 1 OFFSET 1 |
| Top N rows per group | ROW_NUMBER() partitioned, filter <= N | Correlated subquery counting greater-than rows |
| Running total | SUM() OVER (ORDER BY ...) | Self-join summing all earlier rows |
| Find duplicate rows | COUNT(*) OVER (PARTITION BY key) then filter > 1 | GROUP BY key HAVING COUNT(*) > 1 |
| Rows in A with no match in B | LEFT JOIN ... WHERE b.id IS NULL | NOT EXISTS subquery |
| Compare row to prior row | LAG() over an ordered window | Self-join on a sequence or date offset |
Worked example: the second-highest salary
Here's the version of the second-highest-salary prompt that handles ties correctly:
-- Second-highest distinct salary (ties share a rank)
WITH ranked AS (
SELECT salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
)
SELECT DISTINCT salary
FROM ranked
WHERE rnk = 2;
Picking DENSE_RANK over ROW_NUMBER is on purpose. If two people share the top salary, DENSE_RANK correctly treats the next distinct salary as second, while ROW_NUMBER would wrongly hand back the second copy of the top salary. Saying that out loud is exactly the kind of reasoning that wins the round.
Where I'd put your time
Here's the bias I'd give you for 2026: spend 70% of your prep on window functions and live narration, not on memorizing isolation levels. I've watched candidates who could recite all four isolation levels still lose the round because they went silent for ninety seconds on a top-N-per-group query. The DENSE_RANK versus ROW_NUMBER tie detail, said out loud, has flipped more borderline decisions than any ACID definition.
You can't fake this part by reading. You have to rehearse writing SQL out loud against a schema you haven't seen. If you want reps without booking a friend for every session, you can walk into your SQL round able to say the answer out loud after drilling live prompts in a mock where a schema appears and you react to a model query in your own words.
How to prepare for SQL interview questions#
This is a focused two-week plan for a new grad who can read SQL but hasn't written it live while someone watches. Squeeze it shorter if you're further along.
- Rebuild the fundamentals against a real schema (days 1-3). Load a sample customers-orders-products database. Write every join type by hand. Write
GROUP BYwithHAVING. Get theWHEREversusHAVINGdifference and the logical evaluation order down until they're automatic. Explain to yourself why each query returns what it does. You're aiming for production, not recognition: you should be able to type a working join with no reference open. - Master window functions (days 4-6). This topic pays off more than any other. Drill
ROW_NUMBER,RANKandDENSE_RANKwithPARTITION BYandORDER BY. Write a running total with an explicitROWS BETWEENframe. Write aLAG/LEADneighbor comparison. Then write top-3-per-category cold. Get past that and you've cleared the highest bar most rounds set. - Drill the six recurring coding patterns (days 7-9). Second-highest value, find duplicates, top N per group, running total, anti-join, self-join comparison. Write each one twice, once with a window function and once with a subquery. Time yourself: under five minutes per query, reading the schema included.
- Learn the optimization story (days 10-12). Understand what an index is and when it helps or hurts. Read one execution plan and learn to tell a full table scan from an index seek. Memorize the three most common causes of a slow query: a missing index on a join or filter column, a function wrapped around an indexed column, and an accidental cross join. This is what separates backend and data-engineer candidates from analysts.
- Rehearse the live coding round out loud (days 13-14). Grab an unfamiliar schema, set a timer, and write queries while you narrate, just like on a shared screen. Open with clarifying questions, build in small steps, then call out edge cases. Do at least eight prompts. The first one feels awkward. By the eighth, talking while typing feels normal, and that's the actual skill the round grades.
- Run two timed mock SQL rounds (end of week 2). Forty-five minutes each. The first mock: concept recall plus three query prompts. The second: one larger schema with a top-N-per-group question and an optimization discussion. Narrate everything. A live interview assistant you can start free (60 minutes a month with no card; Pro is $29 a month) can pose a fresh schema on demand and give you a quiet model answer to react to, so a full rep costs the price of a coffee instead of a friend's evening.
Step five is the one you can't skip. Interviewers can tell within the first minute whether you've written SQL live before or only studied it, and the only way to build that is doing the reps.
Common mistakes#
These are the mistakes that sink the most new-grad SQL rounds in the 2025-2026 hiring cycle, each with its fix:
- Filtering a
LEFT JOINinWHEREand quietly losing the unmatched rows. Fix: put right-table conditions in theONclause when you need to keep the NULL rows, and double-check by asking yourself whether a row with no match should survive. - Putting an aggregate in
WHEREinstead ofHAVING. Fix: remember the logical order. Aggregation happens afterWHERE, so any condition onCOUNT,SUMorAVGgoes inHAVING. Saying the evaluation order out loud stops this from happening live. - Trying to filter on a window function in the same
SELECT. Fix: window functions are computed afterWHERE, so wrap the query in a CTE or subquery and filter on the aliased column. This is the number-one bug in live top-N-per-group attempts. - Reciting index definitions but never naming the trade-off. Fix: end every indexing answer with "indexes speed reads and slow writes," then say when you would and wouldn't add one. Definitions with no trade-off sound memorized.
- Writing the whole query in silence, then hoping it runs. Fix: narrate the plan first, build in small pieces, and run after each one. A correct silent query scores lower than a correct narrated one, and building step by step catches your own mistakes before the interviewer does.
Related guides#
- Data engineer interview questions: the role that tests SQL optimization, warehousing and pipeline design in the most depth.
- Data analyst interview questions: the loop where the live SQL query-writing round sits at the center.
- Python interview questions: the language most data and backend roles pair with SQL for scripting and analysis.
- System design basics for new grads: where indexing, normalization and the SQL-versus-NoSQL choice show up as architecture decisions.
About the author: Sam K. is the founder of InterviewChamp.AI, building AI interview prep for the new-grad CS market and writing about the modern interview gauntlet from the inside.
Originally published on InterviewChamp.AI
Related guides
CoderPad Alternatives 2026: 6 Tools — Platform Swap or Candidate Help?
CoderPad is the live-coding interview platform that recruiters and hiring managers use to run human-led technical rounds in 2026. Most people searching for CoderPad alternatives are doing one of two things: an employer shopping for a different platform to run interviews on, or a candidate looking for help with a CoderPad round they have coming up. This guide covers both. Six tools compared honestly, with InterviewChamp positioned as the candidate-side helper for practice and, where the company allows it, for live coding rounds on any platform, not just CoderPad.
Sam K. ·
Read more →Interview Sidekick Alternatives in 2026: 6 Tools Compared (Sales + General Interviews)
Interview Sidekick is an AI interview assistant for job candidates: live answers on a call, mock interviews and a 16,000-question bank. People who search for an alternative usually want a different price, a different mix of rounds, or a tool whose rules they are comfortable with. This guide compares six honest options on pricing, real-time speech and round coverage, and marks where InterviewChamp.AI is one of them.
Sam K. ·
Read more →How to Prepare for a Panel Interview: Tips and Sample Questions
A panel interview is a single round where two to six interviewers question one candidate at the same time. Most often: a hiring manager, an engineering manager, a senior engineer, and a bar-raiser. For a CS new grad in 2026, the panel format is harder than a 1:1 not because the questions are harder but because four people watching you at once shrinks the recall-and-articulation window that already breaks under pressure. This guide covers the format, the 4-person hiring-committee configuration, the questions each panelist actually asks, the eye-contact and addressing tactics that don't get taught in school, and the panel-specific thank-you-email discipline that recruiters now flag when it's missing.
Sam K. ·
Read more →Frequently asked questions
- What SQL interview questions should I expect in 2026?
- Expect three buckets. Concept recall (joins, normalization, ACID, the difference between WHERE and HAVING) makes up roughly 30-40% and screens out people who only memorized syntax. The live SQL coding round (write a query against a given schema while someone watches) is 40-50% and is where most rounds are decided. Optimization reasoning (why is this query slow, where would you add an index, read this execution plan) is 15-25% and rises sharply for data-engineer and backend roles. Entry-level analyst loops lean toward query writing; backend and data-platform loops lean toward optimization.
- What are the most common SQL coding interview questions?
- The recurring patterns are: find the second-highest or Nth-highest value, find duplicate rows, get the top N rows per group, calculate a running total or moving average, find rows in table A with no match in table B, and write a self-join to compare a row to a prior row. Most live SQL coding questions are a variation on one of these six. If you can write each of them cold using a window function and using a plain subquery, you cover the majority of what gets asked in the 2025-2026 hiring cycle.
- What is the difference between an INNER JOIN and a LEFT JOIN?
- An INNER JOIN returns only rows that have a match in both tables. A LEFT JOIN returns every row from the left table plus the matching rows from the right table, filling the right-side columns with NULL where there is no match. The interview-relevant trap is filtering a LEFT JOIN in the WHERE clause: putting a condition on the right table in WHERE silently turns the LEFT JOIN back into an INNER JOIN because NULL rows fail the condition. Put right-table conditions in the ON clause instead when you want to keep unmatched left rows.
- What is database normalization and why do interviewers ask about it?
- Normalization is organizing tables to reduce redundancy and prevent update anomalies, usually described in normal forms. First normal form removes repeating groups, second removes partial dependencies on a composite key, and third removes transitive dependencies (non-key columns depending on other non-key columns). Interviewers ask because it reveals whether you understand why a schema is shaped the way it is. The honest senior answer also covers denormalization: read-heavy analytics systems deliberately denormalize to avoid expensive joins, so the right answer is rarely 'always normalize to the highest form.'
- What are window functions and when do you use them?
- A window function performs a calculation across a set of rows related to the current row without collapsing them into one row, unlike GROUP BY which collapses groups into a single row each. You use the OVER clause to define the window, optionally with PARTITION BY to reset per group and ORDER BY to define ordering. Common uses: ranking rows (ROW_NUMBER, RANK, DENSE_RANK), running totals (SUM OVER an ordered window), and comparing a row to a neighbor (LAG, LEAD). They are the single highest-leverage SQL topic to drill because top-N-per-group and running-total questions appear in most live coding rounds.
- What is ACID in databases?
- ACID is four guarantees a transaction provides. Atomicity means all statements in the transaction succeed or none do. Consistency means the transaction moves the database from one valid state to another, respecting constraints. Isolation means concurrent transactions do not interfere, governed by isolation levels. Durability means once committed, the change survives a crash. Interviewers ask ACID to test whether you understand why you wrap a multi-step money transfer in a transaction: without atomicity, a crash mid-transfer could debit one account without crediting the other.
- What is the difference between WHERE and HAVING in SQL?
- WHERE filters individual rows before any grouping happens. HAVING filters groups after a GROUP BY has aggregated them. You cannot use an aggregate like COUNT or SUM in a WHERE clause because the aggregation has not happened yet, but you can in HAVING. A common interview question is 'find customers with more than five orders' which requires GROUP BY customer then HAVING COUNT bigger than five. Putting that count in WHERE is the classic mistake that signals shaky fundamentals.
- When should I use a CTE instead of a subquery?
- A CTE (common table expression, the WITH clause) and a subquery often produce the same result, so the choice is usually about readability and reuse. Use a CTE when the same derived result is referenced more than once, when you are nesting logic three or more levels deep, or when you need a recursive query, which only CTEs support. Use an inline subquery for a single, simple, one-off filter. Modern query planners optimize both similarly in most engines, so the decision is rarely about raw speed for typical workloads.
- How do I prepare for a SQL interview as a new grad?
- Spend two weeks. Week one: rebuild the fundamentals (join types, GROUP BY versus HAVING, normalization, ACID) and write each by hand against a sample schema. Week two: drill the six recurring coding patterns and the optimization story (indexes, execution plans, common slow-query causes). The non-negotiable step is writing SQL out loud against a real schema while narrating your logic, because the live coding round tests whether you can produce a query under observation, not whether you can recognize a correct one in a multiple-choice quiz.
- Do SQL interviews allow you to look things up?
- It depends on the format. Take-home SQL assessments and many remote screens let you use documentation and a real database to test your query. Live coding rounds, especially on a shared screen, usually expect you to write a working query without looking up exact syntax, though most interviewers will give you a function name if you describe what you want. The safest preparation is to know the core syntax cold (joins, GROUP BY, window functions, CTEs) so you are not dependent on lookups when the format does not allow them.