SQL Interview Questions
Relational database mastery: SQL query optimization, transaction isolation levels (ACID), B-Tree vs LSM indexing, locking strategies, and execution plan analysis.
Practice SQL Interview Questions
Showing 16 of 16 technical questions with engineering explanations
What is the logical execution order of a SQL SELECT statement, and why does it matter for aliases and filtering?
Senior Engineering Answer
Although SQL is written starting with SELECT, the database engine logically evaluates clauses in this order: (1) FROM and JOINs (producing the working row set), (2) WHERE (filtering individual rows), (3) GROUP BY (forming groups), (4) HAVING (filtering groups), (5) SELECT (evaluating expressions, window functions, and aliases), (6) DISTINCT, (7) ORDER BY, and (8) LIMIT / OFFSET. Because SELECT executes after WHERE and GROUP BY, column aliases defined in SELECT cannot be referenced in WHERE (or standard HAVING) and window functions cannot appear in WHERE.
SELECT department_id, COUNT(*) AS emp_count FROM employees WHERE hired_at >= DATE '2024-01-01' GROUP BY department_id HAVING COUNT(*) >= 5 ORDER BY emp_count DESC LIMIT 10;
Filtering on an aggregate in WHERE (`WHERE COUNT(*) > 5`) or referencing a SELECT alias in WHERE (`SELECT price * 1.1 AS taxed ... WHERE taxed > 100`), both of which fail because WHERE runs before GROUP BY and SELECT.
Explain the difference between WHERE and HAVING, and how COUNT(*) behaves differently from COUNT(column)?
Senior Engineering Answer
WHERE filters raw rows before grouping and aggregation occur, allowing indexes to prune rows early; HAVING filters summarized groups after GROUP BY has run. Meanwhile, `COUNT(*)` counts every row in the group including rows with NULL columns, whereas `COUNT(column_name)` counts only rows where `column_name IS NOT NULL`, and `COUNT(DISTINCT column_name)` counts unique non-NULL values.
SELECT customer_id,
COUNT(*) AS total_orders,
COUNT(coupon_code) AS orders_with_coupon
FROM orders
WHERE status = 'completed'
GROUP BY customer_id
HAVING COUNT(*) > 3;Putting non-aggregate row filters (like `status = 'completed'`) inside HAVING instead of WHERE: this forces the engine to group all rows (including cancelled orders) before discarding them and prevents index pruning.
Why does placing a filter on the right-hand table inside WHERE turn a LEFT JOIN into an INNER JOIN?
Senior Engineering Answer
In a `LEFT JOIN B ON A.id = B.a_id`, unmatched rows from A are preserved with NULLs in all columns of B. If you then add `WHERE B.status = 'active'`, any unmatched row has `B.status` equal to NULL; since `NULL = 'active'` evaluates to UNKNOWN (falsy), WHERE discards all unmatched rows and silently turns the query into an INNER JOIN. To filter the joined table while preserving unmatched rows from A, place `B.status = 'active'` inside the `ON` clause.
-- Preserves users who have zero paid orders: SELECT u.id, o.id AS paid_order_id FROM users u LEFT JOIN orders o ON o.user_id = u.id AND o.status = 'paid';
Writing `WHERE o.status = 'paid' OR o.id IS NULL` as a workaround when `o.status` itself can be NULL—putting the predicate in the `ON` clause is cleaner and avoids subtle NULL edge cases.
How does SQL three-valued logic (TRUE, FALSE, UNKNOWN) affect NULL comparisons and NOT IN subqueries?
Senior Engineering Answer
SQL uses three-valued logic where any comparison with NULL (`x = NULL`, `x != NULL`) evaluates to UNKNOWN rather than TRUE or FALSE; WHERE only keeps rows evaluating to TRUE. Consequently, `x NOT IN (1, 2, NULL)` expands to `x != 1 AND x != 2 AND x != NULL`, which evaluates to UNKNOWN for every single row and returns ZERO rows! Always use `IS NULL` / `IS NOT NULL`, `IS DISTINCT FROM`, or prefer `NOT EXISTS` over `NOT IN` when subqueries can return NULLs.
-- Safe anti-join even when orders.user_id contains NULLs:
SELECT u.id
FROM users u
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.user_id = u.id
);Using `WHERE col NOT IN (SELECT nullable_col FROM other_table)` in production: a single NULL inserted into `nullable_col` silently empties the entire query result.
Compare ROW_NUMBER(), RANK(), and DENSE_RANK(), plus window frame clauses (ROWS vs RANGE).
Senior Engineering Answer
Window functions compute calculations across a sliding partition of rows without collapsing them like GROUP BY. Given tied values `(100, 100, 90)`: `ROW_NUMBER()` assigns unique sequential numbers `(1, 2, 3)` arbitrarily among ties; `RANK()` assigns `(1, 1, 3)` leaving gaps; `DENSE_RANK()` assigns `(1, 1, 2)` without gaps. Inside `OVER (ORDER BY ...)`, `ROWS BETWEEN 6 PRECEDING AND CURRENT ROW` counts physical rows, whereas `RANGE BETWEEN ...` groups peer rows with identical ORDER BY values (and is the default when ORDER BY is present without an explicit frame!).
SELECT day,
revenue,
AVG(revenue) OVER (
ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS rolling_7d_avg
FROM daily_sales;Writing `SUM(amount) OVER (ORDER BY created_at)` expecting a per-row sum or forgetting that omitting `ROWS BETWEEN` defaults to `RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`, which aggregates tied timestamps together.
What makes a SQL predicate SARGable, and what common query patterns break index usage?
Senior Engineering Answer
SARGable (Search ARGument-able) predicates allow the query optimizer to seek directly into a B-Tree index range rather than scanning every row. Index seeks break when: (1) wrapping an indexed column in a function (`WHERE YEAR(created_at) = 2026` or `LOWER(email) = ...`), (2) performing arithmetic on the column (`WHERE price * 1.1 > 100`), (3) using leading wildcards (`LIKE '%gmail.com'`), or (4) triggering implicit type conversions (comparing a VARCHAR column against an integer literal `WHERE phone = 5551234`). Rewrite predicates to isolate the raw indexed column on one side of the operator.
-- Non-SARGable: WHERE EXTRACT(YEAR FROM created_at) = 2026 -- SARGable range seek: SELECT id, total FROM orders WHERE created_at >= TIMESTAMP '2026-01-01 00:00:00' AND created_at < TIMESTAMP '2027-01-01 00:00:00';
Using `OR` across two different columns (`WHERE a = 1 OR b = 2`) without separate compatible index plans or rewriting as `UNION ALL`: optimizers often fall back to a full table scan when `OR` predicates span unrelated columns.
How do composite B-Tree indexes follow the leftmost prefix rule, and what is a covering index (Index-Only Scan)?
Senior Engineering Answer
A composite B-Tree index on `(tenant_id, status, created_at)` sorts rows lexicographically by `tenant_id`, then `status`, then `created_at`. It efficiently serves queries filtering on `(tenant_id)`, `(tenant_id, status)`, or `(tenant_id, status, created_at)`, and stops using subsequent index columns for range lookups after the first range predicate (`>`, `<`, `BETWEEN`). Put equality columns first and range/sort columns last. A covering index (via extra key columns or `INCLUDE (total)` in PostgreSQL/SQL Server) holds all columns needed by `SELECT` and `WHERE` in the index leaf pages, enabling an Index-Only Scan without touching table heap pages.
-- Supports WHERE tenant_id = ? AND status = ? ORDER BY created_at DESC without heap fetch CREATE INDEX idx_orders_tenant_status_created ON orders (tenant_id, status, created_at DESC) INCLUDE (total_cents);
Creating an index on `(created_at, tenant_id)` for queries filtering `tenant_id = 42 AND created_at >= '...'`: because `created_at` is a range column first, the engine cannot jump straight to `tenant_id = 42` within a single contiguous range.
Why does OFFSET/LIMIT pagination degrade on deep pages, and how does keyset (cursor) pagination fix it?
Senior Engineering Answer
`OFFSET 100000 LIMIT 20` forces the database to scan, sort, and discard 100,000 rows just to return 20, making latency grow linearly with page depth—and concurrently inserted/deleted rows cause skipped or duplicated items across pages. Keyset (cursor) pagination remembers the last seen tie-broken sort key `(created_at, id)` and seeks directly via `WHERE (created_at, id) < (:last_ts, :last_id) ORDER BY created_at DESC, id DESC LIMIT 20`, executing in O(log N) constant time using a composite index.
SELECT id, created_at, title FROM posts WHERE (created_at, id) < (TIMESTAMP '2026-05-01 12:00:00', 98421) ORDER BY created_at DESC, id DESC LIMIT 20;
Using keyset pagination on a non-unique column like `created_at` alone without an `id` tie-breaker: rows with identical timestamps will be silently skipped on the next page.
Explain the four ANSI SQL transaction isolation levels and the anomalies (dirty, non-repeatable, phantom, write skew) they allow or prevent.
Senior Engineering Answer
ANSI SQL defines: (1) Read Uncommitted (allows dirty reads of uncommitted writes), (2) Read Committed (prevents dirty reads; each statement sees latest committed data, allowing non-repeatable reads and phantoms), (3) Repeatable Read (prevents dirty and non-repeatable reads; ANSI allows phantoms, though MVCC Snapshot Isolation engines like PostgreSQL prevent phantoms too while still allowing Write Skew), and (4) Serializable (equivalent to sequential execution, preventing all anomalies including Write Skew). Write skew occurs when two concurrent transactions read an overlapping snapshot, check an invariant (e.g., at least one doctor stays on-call), and update disjoint rows so both commit and violate the invariant.
-- Preventing write skew under Snapshot Isolation using pessimistic row locking or SERIALIZABLE BEGIN ISOLATION LEVEL SERIALIZABLE; SELECT COUNT(*) FROM shifts WHERE is_on_call = TRUE; -- Update proceeds only if serializability check passes at COMMIT
Assuming `REPEATABLE READ` works identically across databases: in PostgreSQL it uses Snapshot Isolation (no phantoms, but allows Write Skew), whereas in MySQL InnoDB it combines MVCC reads with Next-Key locking for locking reads.
Compare the three primary physical JOIN algorithms: Nested Loop Join, Hash Join, and Sort-Merge Join.
Senior Engineering Answer
A Nested Loop Join iterates each outer row and probes the inner table (ideally via an index seek); it excels for small outer sets joined into a large indexed inner table or non-equijoins (`<`, `BETWEEN`). A Hash Join builds an in-memory hash table on the smaller input's join keys and streams the larger input to probe it in O(M + N) time; it excels for large unindexed equijoins, but spills to disk if `work_mem`/join buffer overflows. A Sort-Merge Join scans two inputs already sorted on the join key (via index order or explicit sort) in a single linear merge pass, handling equijoins and order preservation efficiently.
-- Hash Join candidate: large analytical join without selective outer filter SELECT c.region, SUM(o.amount) FROM orders o JOIN customers c ON c.id = o.customer_id GROUP BY c.region;
Forgetting that missing statistics (`ANALYZE`) can trick the optimizer into choosing a Nested Loop Join over millions of outer rows—turning a 200ms Hash Join into a 20-minute query.
How do CTEs (WITH clauses) behave regarding optimization fences vs inlining, and how do Recursive CTEs execute?
Senior Engineering Answer
Historically (e.g., PostgreSQL < 12), non-recursive CTEs acted as optimization fences: materialized once into an internal temp buffer, preventing outer WHERE predicates from pushing down into the CTE. Modern engines (PostgreSQL 12+, MySQL 8+, SQL Server) inline non-referenced/single-use CTEs like subqueries unless explicitly forced (`AS MATERIALIZED` in Postgres) or referenced multiple times. Recursive CTEs (`WITH RECURSIVE`) evaluate an anchor (non-recursive) query into a working table, then repeatedly execute the recursive term against the working table via `UNION ALL` until it produces zero new rows.
WITH RECURSIVE org_tree AS (
SELECT id, manager_id, name, 0 AS depth
FROM employees WHERE id = 1
UNION ALL
SELECT e.id, e.manager_id, e.name, t.depth + 1
FROM employees e
JOIN org_tree t ON e.manager_id = t.id
WHERE t.depth < 10
)
SELECT * FROM org_tree;Writing a recursive CTE over graph data with cycles without a depth cap (`t.depth < 10`) or cycle-tracking (`CYCLE` clause / visited path check), causing an infinite loop until max recursion depth aborts.
Compare MVCC (Multi-Version Concurrency Control) vs lock-based concurrency, and explain read/write trade-offs.
Senior Engineering Answer
Under pure two-phase locking (2PL), readers acquire shared locks that block writers and writers acquire exclusive locks that block readers, causing severe contention on mixed OLTP workloads. Under MVCC (used by PostgreSQL, MySQL InnoDB, Oracle), writers create new row versions tagged with transaction IDs while keeping old versions (in heap tuples or undo logs), and readers read a consistent snapshot as of their transaction/statement start time without acquiring row locks—so readers never block writers and writers never block readers. The trade-off is version cleanup overhead (PostgreSQL `VACUUM` for dead tuples or InnoDB purge threads for undo logs).
-- Long-running analytical transactions hurt MVCC engines: -- Postgres cannot VACUUM dead tuples created after the oldest open snapshot, -- and InnoDB undo history grows until long transactions commit/rollback.
Opening an idle transaction (`BEGIN; SELECT ...;`) in a service and holding it open while making external HTTP calls: this pins the MVCC snapshot horizon and causes severe table/undo bloat.
How do query planners estimate selectivity, and why do correlated columns and data skew cause catastrophic plans?
Senior Engineering Answer
Cost-based optimizers estimate intermediate row counts using table histograms, most-common-value (MCV) lists, and distinct counts (`n_distinct`), typically assuming column independence: `P(A AND B) = P(A) * P(B)`. When columns are strongly correlated (e.g., `make = 'Honda' AND model = 'Civic'`), multiplying selectivities drastically underestimates row counts (1/100 * 1/100 = 1/10,000 instead of 1/100), causing the planner to choose a Nested Loop Join that actually runs millions of loops. Similarly, heavy skew (`tenant_id = 1` has 90% of rows while others have 10 rows) makes generic parameter plans fail unless extended multivariate statistics (`CREATE STATISTICS`) or plan-per-value binding are used.
-- PostgreSQL extended statistics capture cross-column correlation CREATE STATISTICS st_vehicle_make_model (dependencies, ndistinct) ON make, model FROM vehicles; ANALYZE vehicles;
Seeing `EXPLAIN` estimate `rows=1` when `EXPLAIN ANALYZE` shows `actual rows=450000` and ignoring it—a 1000x+ cardinality misestimate is the #1 root cause of sudden query plan regressions.
How do you prevent database deadlocks in high-concurrency OLTP workloads, and compare pessimistic vs optimistic locking?
Senior Engineering Answer
Deadlocks occur when Transaction A holds Lock X and waits for Lock Y while Transaction B holds Lock Y and waits for Lock X. Prevent them structurally by acquiring locks in a deterministic canonical order (e.g., sort account IDs ascending before `SELECT ... FOR UPDATE`), keeping transactions short, and avoiding user/network I/O inside transactions. For low-contention updates, optimistic concurrency control adds a `version` column (`UPDATE items SET qty = qty - 1, version = version + 1 WHERE id = ? AND version = ?`) and retries on 0 affected rows without holding locks; for high-contention rows (like hot inventory counters), pessimistic `SELECT ... FOR UPDATE` (or `SKIP LOCKED` for job queues) prevents retry storms.
-- Job queue worker pattern avoiding lock contention via SKIP LOCKED:
WITH next_job AS (
SELECT id FROM jobs
WHERE status = 'queued'
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE jobs SET status = 'running' WHERE id IN (SELECT id FROM next_job)
RETURNING *;Building a database-backed worker queue with plain `SELECT ... FOR UPDATE` without `SKIP LOCKED`: all worker threads serialize behind the single locked row at the head of the queue.
Compare database Partitioning (range/hash/list) vs Sharding: when does partitioning actually improve performance?
Senior Engineering Answer
Partitioning splits one logical table into smaller physical segments inside a single database node, whereas sharding distributes data horizontally across independent database servers (scaling write throughput and storage beyond one machine, at the cost of distributed transactions and cross-shard joins). Partitioning does NOT automatically speed up point lookups compared to a well-indexed table; its primary wins are partition pruning for time-range analytical scans, instant `DROP PARTITION` / `DETACH` data retention without vacuum/delete bloat, and keeping hot recent partition indexes resident in RAM.
-- Time-range partitioning makes retention an O(1) metadata drop instead of slow DELETEs
CREATE TABLE events (
id BIGINT NOT NULL,
occurred_at TIMESTAMPTZ NOT NULL,
payload JSONB
) PARTITION BY RANGE (occurred_at);Partitioning a table by a column not included in primary/unique keys or common `WHERE` clauses: queries without the partition key must scan every partition (`N` B-Trees instead of 1), making point lookups slower.
How do you perform zero-downtime schema migrations (adding columns, NOT NULL constraints, indexes, and column drops) on massive production tables?
Senior Engineering Answer
Naive `ALTER TABLE` commands can acquire an `ACCESS EXCLUSIVE` lock, queuing behind long-running queries and stalling every incoming read/write behind the lock queue. Safe zero-downtime migrations follow expand-and-contract: (1) set short `lock_timeout` and `statement_timeout` with retries so DDL never piles up traffic, (2) build indexes concurrently (`CREATE INDEX CONCURRENTLY` in Postgres / `ALGORITHM=INPLACE, LOCK=NONE` in MySQL), (3) add `NOT NULL` or `CHECK` constraints as `NOT VALID` first then `VALIDATE CONSTRAINT` under a weak lock, and (4) deploy code that stops reading/writing a column before dropping it.
-- Postgres zero-downtime NOT NULL check without full table write-lock SET lock_timeout = '2s'; ALTER TABLE orders ADD CONSTRAINT chk_tenant_nn CHECK (tenant_id IS NOT NULL) NOT VALID; ALTER TABLE orders VALIDATE CONSTRAINT chk_tenant_nn;
Running `ALTER TABLE big_table ADD COLUMN x INT NOT NULL DEFAULT 0` on older engines without fast-default metadata support, or adding a `CHECK` / `FOREIGN KEY` directly without `NOT VALID`, which holds an exclusive lock while scanning every row.
SQL Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis SQL preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Databases & Storage.
What is the logical execution order of a SQL SELECT statement, and why does it matter for aliases and filtering?
Explain the difference between WHERE and HAVING, and how COUNT(*) behaves differently from COUNT(column)?
Why does placing a filter on the right-hand table inside WHERE turn a LEFT JOIN into an INNER JOIN?
How does SQL three-valued logic (TRUE, FALSE, UNKNOWN) affect NULL comparisons and NOT IN subqueries?
Compare ROW_NUMBER(), RANK(), and DENSE_RANK(), plus window frame clauses (ROWS vs RANGE).
What makes a SQL predicate SARGable, and what common query patterns break index usage?
Frequently Asked Technical Interview Questions (SQL)
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
What are the four ANSI SQL transaction isolation levels and what anomalies do they prevent?
What is the difference between a Sequential Scan, Index Scan, and Index-Only Scan?
How do ROW_NUMBER(), RANK(), and DENSE_RANK() handle ties?
Why does WHERE differ from HAVING in SQL aggregation queries?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.