Databases and SQL interview questions with a live practice quiz

Reviewed by Mark Dickie · Last updated

6 questions on this page you can answer and see marked on the spot. Go to the first one

Databases and SQL are the tools developers use to store structured data and ask questions of it in a declarative language. Interviewers mostly check whether you can write joins, aggregates, and subqueries correctly, and whether you know what the engine does with an index, a transaction, or a NULL. Be ready to explain isolation levels and normalization in terms of the specific anomalies each one prevents.

What does a SQL interview test?

TopicWhat interviewers probe
JOIN typesHow an inner join and a left join differ when a key has no match, and where a filter belongs in an outer join
IndexesB-tree lookups, column order in a composite index, and why wrapping an indexed column in a function can skip the index
TransactionsBEGIN, COMMIT, ROLLBACK, and which isolation level allows dirty or non-repeatable reads
NULL handlingThree-valued logic, why NULL = NULL is not true, and how COUNT(*) differs from COUNT(column)
NormalizationThird normal form, and when denormalizing a reporting table is the right trade

Which steps should you take before the interview?

  1. Write an inner join, a left join, and a NOT EXISTS anti-join against the same two tables, then compare the row counts.
  2. Run EXPLAIN on a query with a range filter, add a composite index, and run it again to see the plan change.
  3. Open two sessions, update the same row in each, and note what READ COMMITTED lets you see that REPEATABLE READ does not.
  4. Find the second-highest salary per department with a window function, then solve it again with a correlated subquery.

Key facts

  • Tarmac has 381 Databases & SQL interview questions on this topic, 10 of them on this page, at difficulty 2–5 of 5.
  • Tarmac tracked 3,405 job postings asking for Databases & SQL in November 2026.
  • Roles asking for Databases & SQL advertise a median base salary of £70,000, across 1,264 job postings as of November 2026.
  • Tarmac last reviewed these Databases & SQL interview questions on 2 November 2026.

At a glance

Questions10 shown · 381 in the bank
Difficulty2–5 of 5
FormatsTrue / false, Code output, Coding exercise, Multiple answer, Fill in the blank, Find the bug, Multiple choice, Ordering, Flashcard, Short answer
Interactive1 run your code against tests, in the app

What you'll review

  1. query planning
  2. select basics
  3. aggregation
  4. db performance
  5. covering index

Practice questions

Try one before you open the answer. Pick an option and press Check; it's marked on the spot.

Consider the query SELECT name FROM users WHERE email = '[email protected]';, where name appears only in the SELECT list and email is the only filtered column. Adding a B-tree index on name (and no index on email) will let the planner perform an index seek to look up rows by email for this query.#

Options

Show answer

A B-tree index on name does not let the planner seek rows by email for WHERE email = ..., because its entries contain no email values to search. The planner may still scan that index in full, but that is not a lookup by email. Efficient lookup requires an index on email.

Why:

The statement is false. An index seek needs an index whose keys include email, so it can jump directly to matching entries. A B-tree index on name holds only name values, so it cannot be used to seek or look up rows by email. The planner could still read the whole name index in full and fetch each table row to check email, which is a full scan rather than a lookup by email, and PostgreSQL rarely chooses it for this query. Efficient lookup by email requires an index on email.

Given employees(name, salary) with rows (Ann, 90), (Bo, 70), (Cy, 90), (Di, 50), what does this query return?#

SELECT name, salary
FROM employees
WHERE salary >= 70
ORDER BY salary DESC, name ASC
LIMIT 2;

Options

Show answer
(Ann, 90), (Cy, 90)
Why:

WHERE salary >= 70 drops Di (50). The remaining three sort by salary DESC first, tying Ann and Cy at 90; the secondary name ASC orders Ann before Cy. LIMIT 2 then keeps the top two: (Ann, 90), (Cy, 90).

The users table has columns id (INTEGER) and email (TEXT). Write a query returning each email address that appears more than once, with columns email and cnt (how many times it appears), ordered by cnt descending, then email ascending.#

Starter code

-- Return: email, cnt (count > 1), ordered by cnt DESC, email ASC
SELECT

Your solution must pass

  • finds both duplicated emails with their counts

This one is written and run, not read. Solve it in the app and your code is executed against these tests and the hidden ones.

You run EXPLAIN ANALYZE on a slow query in PostgreSQL. Which of the following are valid and actionable insights you can directly obtain from its output? Select all that apply.#

Options

Pick every one that applies.

Show answer

From EXPLAIN ANALYZE output you can directly learn: the access method chosen for each table (Sequential Scan vs. Index Scan), estimated vs. actual row counts at every plan node — crucial for spotting stale statistics — and the total wall-clock execution time. Network latency between client and server and specific OS page-cache blocks read are not reported in EXPLAIN ANALYZE output.

Why:

EXPLAIN ANALYZE executes the query and annotates each plan node with estimated cost/rows, actual rows returned, and actual timing (wall-clock time per node and total). This lets you identify bad row-count estimates (estimated vs. actual rows) and expensive nodes (total wall-clock execution time). Network latency is outside the scope of the query planner output entirely. Buffer/block-level cache statistics are only visible with EXPLAIN (ANALYZE, BUFFERS) and even then show buffer hit counts, not specific block addresses.

In PostgreSQL, after loading millions of new rows into a table, the query planner may choose poor plans because its internal _____ for that table are stale. Running the single-keyword PostgreSQL SQL command _____ on the table refreshes them (do not use VACUUM ANALYZE). Separately, if a WHERE clause is estimated to match a very large fraction of the table, the planner's estimated fraction of matching rows, a value between 0 and 1 known as _____, is large, and the planner may prefer a sequential scan over an index scan.#

Show answer

In PostgreSQL, after loading millions of new rows into a table, the query planner may choose poor plans because its internal statistics for that table are stale. Running the single-keyword PostgreSQL SQL command **ANALYZE** on the table refreshes them (do not use VACUUM ANALYZE). Separately, if a WHERE clause is estimated to match a very large fraction of the table, the planner's estimated fraction of matching rows, a value between 0 and 1 known as selectivity, is large, and the planner may prefer a sequential scan over an index scan.

Why:

This is PostgreSQL-specific. The planner estimates row counts and value distributions from its planner statistics: per-table figures such as reltuples and relpages live in pg_class, and detailed per-column value distributions live in pg_statistic. After a large bulk load these estimates can be badly out of date, so the planner's row estimates go wrong. Running the standalone ANALYZE command samples the table and refreshes those statistics; VACUUM ANALYZE is excluded by the wording because the question asks for the single-keyword command. Separately, selectivity is the fraction of a table's rows that a predicate matches, so a predicate estimated to match a large share of rows has a large selectivity value; because reading most of the table through an index means many random page reads, the planner often prefers a sequential scan in that case.

A developer adds the following index and query to power a leaderboard page that should show the top 10 players (highest scores) for a given game. The query returns incorrect results. Identify the line that contains the bug.#

CREATE INDEX idx_leaderboard
    ON player_scores (game_id, score);

SELECT player_id, score
FROM   player_scores
WHERE  game_id = 7
ORDER BY score ASC
LIMIT  10;

Options

Show answer

Line 7 — ORDER BY score ASC returns the 10 lowest scores; it should be ORDER BY score DESC to retrieve the top (highest) 10 scores

Why:

The intent is to fetch the top 10 players by highest score, making this a leaderboard. ORDER BY score ASC LIMIT 10 is a purely logical bug: it returns the 10 lowest scores, not the highest. Changing it to ORDER BY score DESC LIMIT 10 fixes the correctness issue. Importantly, B-tree indexes on (game_id, score) support both forward (ASC) and backward (DESC) scans with equal efficiency — modern optimizers (PostgreSQL, MySQL, SQL Server) simply traverse the index leaf pages in the opposite direction for DESC, incurring no extra cost. So the bug is entirely about correctness, not performance. The claim that the index should be on (score, game_id) instead of (game_id, score) is wrong: (game_id, score) is the correct column order — placing the equality-filtered column (game_id) first and the sort column (score) second is the standard pattern for this access pattern. The claim that LIMIT is incompatible with indexed lookups and should be removed is wrong: LIMIT actually enables an early-stop optimization, reducing work. The claim that WHERE game_id = 7 should use a range predicate (e.g., game_id >= 7) to allow the index to be used is wrong: WHERE game_id = 7 is an exact equality predicate, which is ideal for the leading index column and allows the index to be used efficiently.

A PostgreSQL table orders has 10 million rows. A B-tree index exists on the status column. The following query ignores the index and performs a sequential scan:#

Options

Show answer

The planner correctly chooses a sequential scan because fetching ~9.4 million rows via random index lookups would be far more expensive than one sequential pass over the heap. PostgreSQL's cost model weights random I/O (random_page_cost) higher than sequential I/O (seq_page_cost), so when a predicate matches a large fraction of rows the index offers no benefit.

Why:

PostgreSQL's query planner chooses between a sequential scan and an index scan based on cost estimates derived from statistics (pg_statistic). When a predicate matches a large fraction of rows (e.g., a low-selectivity condition like status = 'active' on a table where 95% of rows are active), the planner correctly decides that reading the entire heap sequentially is cheaper than random index lookups plus heap fetches. The planner uses the page-level cost model: random I/O has a higher cost constant (random_page_cost) than sequential I/O (seq_page_cost). An index is only beneficial when selectivity is high (few rows returned). Options about outdated statistics (ANALYZE not run) and fillfactor are distractors — the described behavior is correct planner behavior, not a bug.

Place the following PostgreSQL query-processing stages in the correct order, from first to last, for a standard SELECT query.#

Put these in order

Show answer

The correct order is: (1) Parser – converts raw SQL into a parse tree; (2) Analyzer & Rewriter – resolves names and expands views; (3) Planner/Optimizer – costs candidate plans and picks the cheapest; (4) Executor – walks the plan tree to produce result rows. Each stage transforms the query representation before handing it to the next.

Why:

The correct sequence for how PostgreSQL processes a query through the planner/optimizer is: (1) Parser – turns SQL text into a parse tree; (2) Analyzer/Rewriter – resolves names, applies rules/views to produce a query tree; (3) Planner/Optimizer – generates and costs candidate plans using statistics, then selects the cheapest; (4) Executor – executes the chosen plan. Understanding this pipeline is essential for diagnosing why plans are chosen and how statistics feed into cost estimation.

What is a covering index, and why is it faster than a normal index lookup?#

Show answer

A covering index contains every column a query needs (in its key or, in PostgreSQL, an INCLUDE clause), so the query is answered entirely from the index. This gives an index-only scan that skips the extra heap/table fetch a normal index lookup needs to retrieve the remaining columns.

Why:

Normally an index points back to the table row to fetch columns it doesn't store, costing an extra read per match. When the index already holds all referenced columns, the engine does an index-only scan and never touches the table — a big win for hot, selective queries.

A table events has ~500 million rows and this composite B-tree index:#

Show answer

In a B-tree, entries are sorted by the full key tuple, so with (status, created_at) all entries for status = 'PENDING' are stored together, and within that block they are sorted by created_at. The equality on the leading column locates one contiguous block, and the condition created_at > NOW() - INTERVAL '7 days' selects a contiguous sub-range at the end of it. Because that sub-range is already ordered by created_at, a backward index scan can return rows in ORDER BY created_at DESC order and stop after 100 matches, so no Sort node is needed.

Why:

With the key order (status, created_at), the index is sorted first by status and then by created_at inside each status value. The equality predicate on status therefore pins down one contiguous block of index entries, and the created_at range is a contiguous sub-range within that block. Entries inside that sub-range are already in created_at order, so the ORDER BY created_at DESC LIMIT 100 can be served by a backward scan of the index that stops after 100 matching rows, avoiding an explicit sort. The argument rests on the sort order of the key tuple, not on how many distinct status values exist.

Sources

The official documentation these questions are checked against:

Related interview questions

Job market

See databases-sql salaries and hiring demand from live job postings.

The other 371 questions

This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 371 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.

Start with this topic

Free · the whole bank · 100 answers per 30 days, each marked with written feedback

Interview booked? Practise the job ad instead

What moved, monthly

One email a month when the bulletin comes out: what moved in the markets we track, and the new question topics we published. Confirm your address to join. Unsubscribe any time.