Skip to content
Sign inGet all access

SQL interview questions for experienced developers

Eleven tricky SQL interview questions with answers — WHERE vs HAVING, LEFT JOIN traps, NOT IN with NULL, query plans, indexes. Every query was really run.

Most SQL interview questions you’ll find online are trivia. Nobody is going to ask you what SQL stands for.

These are the tricky ones you actually get asked as an experienced developer, with answers and the follow-up that tells the interviewer whether you’ve really used this stuff. Every query below was run before it went up — the output you see is the real output, not something typed from memory.

1. What is the difference between WHERE and HAVING?

Most people say “HAVING filters groups, WHERE filters rows”. That’s true, but the answer they’re after is when each one runs. WHERE goes first, before anything is grouped, so it can’t see a COUNT yet. HAVING comes after the grouping, so it can.

SELECT city, COUNT(*) AS n
FROM customer
WHERE active = 1
GROUP BY city
HAVING COUNT(*) > 1;
Output+-------+---+| city | n |+-------+---+| Delhi | 2 |+-------+---+

Inactive customers go first. What’s left gets grouped by city. Only then do cities with a single customer get dropped.

Try moving active = 1 into the HAVING and you’ll get a different count — those rows were still sitting there when the counting happened.

More on this in Aggregates and Grouping.

2. When does a LEFT JOIN behave like an INNER JOIN?

The moment you put a WHERE on the nullable side. This one ships to production more often than you’d think.

Two tables: customer, and sale with an amount on each row. Alan is a customer who has never bought anything.

SELECT c.name, s.amount
FROM customer c
LEFT JOIN sale s ON s.customer_id = c.id
WHERE s.amount > 10;
Output+-------+--------+| name | amount |+-------+--------+| Ada | 49.99 || Ada | 19.95 || Grace | 189.95 |+-------+--------+

The join does its job: Alan gets a row, with NULL where his amount would be. Then the WHERE asks whether NULL > 10, which isn’t true, and his row disappears.

You wrote a LEFT JOIN and got an INNER JOIN, with nothing to tell you.

Put the condition in the ON instead. Now it decides what gets joined, not what survives afterwards:

SELECT c.name, s.amount
FROM customer c
LEFT JOIN sale s
  ON s.customer_id = c.id AND s.amount > 10;
Output+-------+--------+| name | amount |+-------+--------+| Ada | 49.99 || Ada | 19.95 || Grace | 189.95 || Alan | |+-------+--------+

Alan is back, blank amount and all.

More on this in Joins.

3. Find the second highest salary in an employee table

Everyone reaches for ORDER BY salary DESC LIMIT 1 OFFSET 1 first. It falls over as soon as two people earn the top salary — skip one row and you’re still looking at the same number.

SELECT DISTINCT salary
FROM employee
WHERE salary IS NOT NULL
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
Output+--------+| salary |+--------+| 95000 |+--------+

DISTINCT is what saves you here. The IS NOT NULL is just belt and braces — engines disagree about where NULLs land in a DESC sort, and spelling it out costs you nothing.

Expect them to follow up with “now do it per department”. That’s a window function:

SELECT dept, name, salary
FROM (
  SELECT dept, name, salary,
         DENSE_RANK() OVER (
           PARTITION BY dept ORDER BY salary DESC
         ) AS rnk
  FROM employee
  WHERE salary IS NOT NULL
) ranked
WHERE rnk = 2;
Output+-------+--------+--------+| dept | name | salary |+-------+--------+--------+| eng | Alan | 95000 || sales | Edsger | 80000 |+-------+--------+--------+

Use DENSE_RANK, not ROW_NUMBER. If two people tie at the top, ROW_NUMBER hands you the second of that pair — still the top salary. You want the next one down.

More on this in CTEs and Window Functions.

4. How do you analyse a slow query and find its bottleneck?

Stop guessing and read the plan. “I’d EXPLAIN it” is most of the answer they want.

terminal
EXPLAIN ANALYZE
SELECT * FROM employee WHERE dept = 'd7';
OutputSeq Scan on employee (cost=0.00..94.50 rows=250 width=18) (actual time=0.012..0.173 rows=250.00 loops=1) Filter: (dept = 'd7'::text) Rows Removed by Filter: 4750 Buffers: shared hit=32Planning Time: 0.176 msExecution Time: 0.184 ms

EXPLAIN on its own tells you what the optimiser plans to do. Add ANALYZE and it actually runs the query, then shows you what really happened. That’s the one you want.

The line that matters here is Rows Removed by Filter: 4750. To hand you 250 rows, the database read all 5000 and threw away the rest. Give it an index and it stops doing that.

terminal
CREATE INDEX idx_dept ON employee(dept);
EXPLAIN ANALYZE
SELECT * FROM employee WHERE dept = 'd7';
OutputBitmap Heap Scan on employee (cost=6.22..41.34 rows=250 width=18) (actual time=0.025..0.048 rows=250.00 loops=1) Recheck Cond: (dept = 'd7'::text) Heap Blocks: exact=32 -> Bitmap Index Scan on idx_dept (cost=0.00..6.16 rows=250 width=0) (actual time=0.019..0.019 rows=250.00 loops=1) Index Cond: (dept = 'd7'::text)Execution Time: 0.084 ms

Same 250 rows, but now it goes through the index instead of walking the table.

So what do you look for? Start with the scan. Every engine names it differently — Seq Scan on PostgreSQL, SCAN on SQLite, type: ALL on MySQL — and seeing one where you expected an index is usually the whole problem.

Then compare the two row counts. EXPLAIN ANALYZE prints what the planner expected next to what it got, and on a table nobody has analysed you’ll see something like rows=18 ... actual rows=50.00. That gap means it’s working from stale statistics and choosing badly because of it. Run ANALYZE — it’s the first thing to try when a query that used to be quick suddenly isn’t.

Last, find the slowest step rather than staring at the total. A plan is a tree, and the time is almost never spread evenly. One join or sort is usually eating all of it. Fix that and stop.

One more thing worth saying out loud, because interviewers like hearing it: an index can sit there unused. Wrap the column in a function (WHERE UPPER(dept) = 'ENG'), start a LIKE with a wildcard ('%eng'), or write a filter that most rows match anyway, and the database will skip it — scanning is cheaper than hopping back and forth between index and table.

More on this in Reading a Query Plan.

5. How do you write an optimised query?

You don’t, not upfront. Write the clearest correct query, then fix it when something is actually slow. Say that first — then show you know the habits.

Cut rows out as soon as you can, so the joins and sorts that come after have less to chew through. Put an index on whatever you filter or join on.

And list the columns you want rather than SELECT *. That one surprises people. An index is a small copy of a few columns, kept sorted. If every column you asked for happens to be in it, the database can answer straight from that copy and never touch the real table.

Say the table has an index on dept and salary, and rows that also carry a name and a long bio:

terminal
EXPLAIN ANALYZE
SELECT * FROM emp3 WHERE dept = 'd7';
OutputIndex Scan using idx3 on emp3 (cost=0.29..8.30 rows=1 width=426) (actual time=0.012..0.012 rows=1.00 loops=1) Index Cond: (dept = 'd7'::text) Buffers: shared hit=1 read=2Execution Time: 0.022 ms

That query wanted name and bio, which the index doesn’t store — so the database had to go and fetch the actual row. Ask for just the two columns the index already has:

terminal
EXPLAIN ANALYZE
SELECT dept, salary FROM emp3 WHERE dept = 'd7';
OutputIndex Only Scan using idx3 on emp3 (cost=0.29..8.30 rows=1 width=10) (actual time=0.007..0.007 rows=1.00 loops=1) Index Cond: (dept = 'd7'::text) Heap Fetches: 1 Buffers: shared hit=3Execution Time: 0.014 ms

Index Scan turned into Index Only Scan — “only” meaning it never left the index. Same filter, same row, but the second one skipped a whole step.

6. What techniques keep SQL fast at scale, for reads and for writes?

They want a list, and they want you to know the two sides fail differently.

On reads:

  • Indexing. Put them on whatever you filter, join and sort by.
  • Fewer columns. Name them instead of SELECT *.
  • Keyset pagination. OFFSET 199000 walks 199,000 rows first. Ask for rows after the last id you saw.
  • Covering indexes. If the index already has every column the query wants, the database never opens the table.
  • Caching and materialised views. Good for expensive aggregates that don’t need to be up to the second.
  • Read replicas. Once one machine stops keeping up with the reads.

On writes:

  • Batch inserts. One statement with many rows, not many statements.
  • One transaction per batch. Every commit waits for the disk.
  • Short transactions. They hold locks until they finish.
  • Fewer indexes. Every one of them gets updated on every write.
  • Bulk-load tools. COPY on PostgreSQL, LOAD DATA INFILE on MySQL.
  • Chunked deletes. Deleting ten million rows in one go is one enormous transaction. Loop it instead.

Two that cut across both:

  • Connection pooling. Opening a connection is expensive — on PostgreSQL it’s a whole new backend process. Reuse a pool instead of one per request.
  • Partitioning and sharding. Say these last. They’re for when the table has outgrown the machine.

7. Find customers who have never bought anything

Ada and Grace have rows in sale. Alan doesn’t.

SELECT c.name
FROM customer c
WHERE NOT EXISTS (
  SELECT 1 FROM sale s WHERE s.customer_id = c.id
);
Output+------+| name |+------+| Alan |+------+

A LEFT JOIN ... WHERE s.id IS NULL gives the same answer and is just as acceptable.

What they’re watching for is whether you reach for NOT IN. If sale.customer_id has even one NULL in it, that version returns no rows at all — not an error, just a silently empty result.

More on this in Subqueries and NULL.

8. How do you add a column with a default to a million-row table in production?

They’re checking whether you understand locks. On PostgreSQL 11+ and MySQL 8 a constant default is stored as metadata, so this is a millisecond operation:

ALTER TABLE orders
  ADD COLUMN status text NOT NULL DEFAULT 'pending';

On an older engine, or with a non-constant default like now(), the table gets rewritten. Then you split it into steps that each take a short lock.

1. Add the column nullable, no default.

ALTER TABLE orders ADD COLUMN status text;

2. Set the default, so new rows get it.

ALTER TABLE orders
  ALTER COLUMN status SET DEFAULT 'pending';

3. Deploy the code that writes the column. Do this while it’s still nullable — old code keeps working, new rows arrive with a value.

4. Backfill in batches, looping until it updates nothing. One big UPDATE would lock every row it touches.

UPDATE orders SET status = 'pending'
WHERE id IN (
  SELECT id FROM orders
  WHERE status IS NULL LIMIT 5000
);

5. Add the constraint as NOT VALID, then validate it separately. A plain SET NOT NULL scans the whole table under an exclusive lock; this splits that into an instant change and a scan under a weaker one.

ALTER TABLE orders ADD CONSTRAINT status_nn
  CHECK (status IS NOT NULL) NOT VALID;

ALTER TABLE orders VALIDATE CONSTRAINT status_nn;

More on this in Schema Design.

9. What is MVCC, and why is it better than locking?

Multi-Version Concurrency Control is how PostgreSQL and MySQL’s InnoDB handle concurrency, instead of locking everything. The database keeps more than one version of a row: an update doesn’t overwrite the old value, it writes a new version alongside it. Every transaction reads from a consistent snapshot of the data as it stood when that transaction started.

The payoff is one sentence: readers don’t block writers, and writers don’t block readers.

terminal
BEGIN;
UPDATE acct SET balance = 500 WHERE id = 1;
-- not committed yet
Outputsession A session B--------- ---------BEGIN;UPDATE acct SET balance = 500 WHERE id = 1; SELECT balance FROM acct WHERE id = 1; -> 100 (returns at once)COMMIT; SELECT balance FROM acct WHERE id = 1; -> 500

Session B asks for the balance mid-update and gets 100 straight away — the version that was committed when its query started. No waiting, and no reading a half-finished write either. Once A commits, B sees 500.

Under pure locking, B would have sat there waiting for A to finish. On a busy table that queue is the bottleneck.

More on this in Transactions.

10. Normalisation vs denormalisation — what are the trade-offs?

Normalisation means storing each fact once, and pointing at it from everywhere else. The customer’s city lives on the customer row, and sale just holds a customer_id.

Denormalisation means deliberately copying that fact where you need it, so the read doesn’t have to go and fetch it.

Aspect Normalised Denormalised
Each fact stored once copied
Reads need joins one table
Writes one row every copy
Storage smaller larger
Risk slow joins copies drift

Normalised wins on correctness. There’s one copy of the city, so it can’t disagree with itself, and you avoid the three classic anomalies: an update that changes some copies and misses others, a customer you can’t insert until they’ve bought something, and a customer who vanishes when you delete their last sale.

What it costs is joins. Ten normalised tables means a ten-way join on the read path, and that’s where it starts to hurt.

Denormalised wins on read speed, which is why reporting tables and caches look the way they do. One table, no joins, fast.

What it costs is every write. Change a customer’s city and you now have to find and update every row that copied it — and if one update fails halfway, your data quietly disagrees with itself.

The answer they want: normalise by default, denormalise when you’ve measured a read path that’s actually too slow, and only where you can keep the copies in step.

More on this in Schema Design.

11. What are the downsides of having indexes?

Mainly two, and both come down to an index being a second copy of your data.

  • Increased storage. Every index you add stores those columns again, in a B-tree or B+ tree. Add enough of them and they can get bigger than the table itself.
  • Slower writes. The database keeps every one of those trees sorted. Add a row and it has to update the table plus each index on it. Same when you update or delete.

Want the long version? The SQL course takes all of this apart chapter by chapter, and every snippet in it was run on PostgreSQL, MySQL and SQLite before it shipped.

Tables