Query Optimization and Execution Plans Questions
Making queries fast: reading and interpreting execution/explain plans, identifying full scans, spotting SQL anti-patterns, and rewriting queries for better performance. Covers how the planner chooses join order and access methods, and how statistics drive those choices. A core skill for anyone responsible for query performance in production.
Compare IN, EXISTS, and JOIN as ways to test membership in another table. Cover how NULLs change the semantics of each (particularly for a large IN list or a NOT IN), when the optimizer is free to transform one into another, and when the choice actually changes performance rather than just readability.
Sample Answer
Direct answer. IN and EXISTS both test membership but differ in how NULLs interact with them and in how each maps onto a join in the optimizer's mind; JOIN differs from both in that it's row-producing rather than boolean, so it only behaves like a membership test if the inner side is guaranteed unique per outer row.
Structured elaboration. WHERE x IN (subquery) is true if x matches any row the subquery returns; critically, if the subquery's result set contains even one NULL and x doesn't match any non-NULL value, the whole expression evaluates to UNKNOWN rather than false, which under NOT IN specifically can silently make the entire outer predicate evaluate to nothing at all (a classic, expensive-to-debug correctness trap, not just a performance one). WHERE EXISTS (correlated subquery) instead asks only "does at least one matching row exist," is unaffected by NULLs in the same way, and lets the engine short-circuit as soon as one match is found rather than materializing a full list to compare against. A plain JOIN used for the same membership-testing purpose can silently change the row count of the outer query if the inner side isn't unique per join key, duplicating outer rows once per match, which neither IN nor EXISTS does since they only ever return true or false.
The optimizer is often free to transform one of these into another internally, when they happen to be logically equivalent for that specific query, so the choice between them is not always a performance decision. Where it genuinely matters, EXISTS's short-circuit behavior tends to help most when only a small fraction of outer rows actually have any match, and its immunity to the NULL trap makes it the generally safer default whenever the inner column can contain NULLs.
Worked example. For customers where you want those with at least one high-value order, IN (SELECT customer_id FROM orders WHERE amount > 1000) and EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.amount > 1000) return identical results as long as customer_id in orders never contains NULL; if it can be NULL and you instead wrote NOT IN (...) to find customers WITHOUT a high-value order, that query can silently return zero rows the moment even one NULL customer_id exists in orders, while the equivalent NOT EXISTS form is unaffected.
Trade-offs and pitfalls. Prefer EXISTS/NOT EXISTS over IN/NOT IN whenever the inner column isn't guaranteed NOT NULL, purely for correctness, independent of any performance difference; and never reach for a plain JOIN as a membership test unless you've confirmed the inner side is unique per join key, or wrap it in a DISTINCT to restore the semantics you actually wanted.
Complexity
All three can, in principle, execute as a semi-join internally when the engine recognizes the pattern, so there is often no fundamental asymptotic difference; the practical differences come from NULL handling and from whether the engine actually recognizes the equivalence for a given query shape.
Edge cases
NOT IN against a column that can contain NULL is the single highest-risk pattern here and deserves an explicit check (or an automatic ban) in code review, since it fails silently rather than with an error.
Compare nested loop, hash, and sort-merge join algorithms: how each works, its memory and I/O profile, and the conditions under which a cost-based optimizer prefers it. What data properties (sorted input, small build side, high join selectivity) make one algorithm clearly better than the others?
Sample Answer
Direct answer. Nested loop is cheapest when the outer side is small and the inner side has a cheap way to be probed (typically an index); hash join is the workhorse for large, unsorted inputs where one side comfortably fits in memory to build a hash table from; sort-merge join wins when both inputs are already sorted (or cheaply sortable) on the join key, since it can then walk both in a single linear pass with no random lookups and no hash table at all.
Structured elaboration. Nested loop's cost is roughly (outer rows) times (cost per inner probe); it degrades badly the moment the outer side is larger than expected, since every extra outer row multiplies the total work. Hash join's cost is roughly (build side rows, to construct the hash table) plus (probe side rows, each a cheap in-memory lookup); its main risk is memory: if the build side is bigger than the memory budget allotted, the hash table spills to disk in partitions, which is far slower than an in-memory hash join but still usually better than a nested loop over the same volumes. Sort-merge needs both inputs sorted; if an index already provides that order, the "sort" part is free and the join itself is a fast linear merge, but if neither input is sorted and both are large, the up-front sort cost can make this the worst of the three options.
Worked example. Joining a 50-million-row fact table to a 200-row lookup table: a nested loop with an index on the fact table's join key (probing the fact table once per lookup row) does roughly 200 cheap index probes, which is far cheaper than building a hash table from 50 million rows. Flip the sizes, joining two roughly-equal, unsorted multi-million-row tables, and a hash join (build from the smaller of the two, probe with the larger) beats a nested loop by orders of magnitude, since nested loop would need tens of millions of probes instead of one hash table build plus one linear probe pass.
Trade-offs and pitfalls. None of the three algorithms is universally best; the right one is a function of the relative sizes of the two inputs, whether either side is already sorted or indexed on the join key, and how much memory is available for a hash table. A senior red flag is seeing a nested loop join over two large, unindexed inputs (that's the shape most likely to be a genuine planner mistake, usually traced back to a cardinality misestimate) versus seeing it over one genuinely small input joined to a large indexed one (that's usually correct and fast).
Write (or describe) how a LATERAL join can replace a correlated subquery when you need, for each row of an outer table, the top result from a related table (for example the most recent event per user, or the top-N per group). Explain why the LATERAL form is usually more optimizer-friendly than the equivalent correlated subquery.
Sample Answer
Direct answer. A LATERAL join lets a subquery on the right-hand side reference columns from a table on the left-hand side of the FROM clause, row by row, which is exactly what you need to compute "the top N related rows per outer row" without a correlated subquery in the SELECT list or a window function over the whole joined result.
Structured elaboration. A LATERAL subquery is evaluated once per row of whatever precedes it in the FROM clause, with that outer row's columns visible inside the subquery, similar in spirit to a correlated subquery but structured as a proper join rather than an expression in the SELECT list, which lets it return multiple rows and columns naturally, and lets the optimizer reason about it more like an ordinary join than an opaque per-row expression.
Worked example. I verified this with two customers and six orders (four for customer 1, two for customer 2), returning the top 3 orders by amount per customer:
SELECT c.customer_id, o.order_id, o.total
FROM customers c,
LATERAL (
SELECT order_id, total
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY total DESC
LIMIT 3
) o
ORDER BY c.customer_id, o.total DESC;
This correctly returned customer 1's top three orders (80, 65, 50, correctly excluding their fourth, smaller order) and customer 2's two available orders (999, 10), confirming the LATERAL subquery's WHERE o.customer_id = c.customer_id correctly re-scoped to each outer row and its own ORDER BY ... LIMIT 3 correctly capped the result per customer, not globally across all customers.
Trade-offs and pitfalls. LATERAL is usually more optimizer-friendly than an equivalent correlated scalar subquery specifically because it's structured as a genuine per-row join the optimizer can index-nest efficiently (an index on orders(customer_id, total) makes each per-customer lookup cheap), rather than an opaque per-row expression the optimizer has less visibility into; it's also a natural fit for "top N per group" specifically because the LIMIT lives inside the LATERAL subquery, scoped per outer row, which a plain window function approach achieves differently (ranking every row, then filtering on rank) with a comparable but structurally different cost profile.
Complexity
With a supporting index on the inner table's join and sort columns, this executes as roughly (outer rows) times (a cheap, index-bounded lookup for N rows), which scales far better than materializing every related row and sorting them all before trimming to N.
Edge cases
An outer row with fewer than N matching inner rows (customer 2's two orders, in the example) correctly returns just those, with no error and no padding, which is worth confirming explicitly since a naive alternative implementation can sometimes mishandle that case.
Explain what a bitmap index scan is and why a planner might choose it over either a plain index scan or a sequential scan. What predicate shapes make it attractive, and what does 'lossy' bitmap behavior mean for very large row estimates?
Sample Answer
Direct answer. A bitmap index scan builds an in-memory bitmap of matching row locations from one or more indexes, then visits the table using that combined bitmap in physical storage order rather than in index order, which lets the planner efficiently combine multiple indexes for one query and avoid the random-access pattern a plain index scan would otherwise pay for at moderate selectivity.
Structured elaboration. A plain index scan visits matching rows in the INDEX's order, which for a moderately selective predicate (not tiny, not huge) can mean visiting the underlying table in scattered, random physical order, one lookup per match. A bitmap scan instead first builds a bitmap marking which table pages (or exact rows, depending on how lossy the bitmap is) contain a match, without immediately visiting the table at all, then does a single pass over the table in PHYSICAL order, checking only the pages the bitmap flagged. This turns what would have been scattered random access into a more sequential, sorted-by-physical-location access pattern, which tends to win specifically in the middle ground of selectivity, too many matches for a plain index scan's random-access pattern to stay cheap, too few for a full sequential scan to be the better choice.
The other place this shines is combining multiple indexes for one query: bitmaps from two different single-column indexes can be combined (via a boolean AND or OR) in memory before ever touching the table, letting the planner efficiently satisfy a multi-column predicate even without a single composite index covering all the relevant columns.
Worked example. A query filtering on two separately-indexed columns with moderate selectivity each, where no composite index covering both exists, can use a bitmap scan on each individual index, AND the two resulting bitmaps together in memory, and then visit only the table pages that satisfy BOTH conditions in one physical-order pass, rather than either falling back to a full table scan or being unable to use both indexes together at all.
Trade-offs and pitfalls. A bitmap can become "lossy" (tracking pages rather than exact rows) once it would otherwise consume too much memory to track every individual matching row precisely, at which point the table visit has to re-check every row on a flagged page against the actual predicate, adding back a small amount of the cost the bitmap was trying to avoid; this is still typically much cheaper than the alternative, but worth knowing about if you're trying to understand exactly why a bitmap scan's actual time doesn't match a naive "just count the matching rows" estimate.
For a large fact table partitioned by a date or key column, explain how partition pruning lets the planner skip entire partitions for a query, and what predicate shapes silently defeat it (a function wrapped around the partition column, a predicate that never mentions the partition key, or a join that doesn't align with partition boundaries). Walk through how you would confirm pruning is or isn't happening for a specific query.
Sample Answer
Direct answer. Partition pruning lets the planner skip reading entire partitions whose range can't possibly satisfy the query's predicate, based purely on partition boundaries, without opening those partitions at all; it silently fails whenever the predicate doesn't let the planner make that boundary comparison directly, most commonly because the partition column is wrapped in a function or absent from the predicate entirely.
Structured elaboration. For a table partitioned by a date or key range, each partition covers a known, non-overlapping slice of that column's values. If a query's WHERE clause directly compares the partition column to a constant or a bound range, the planner can compare that predicate against each partition's known boundaries at planning time and discard any partition that can't possibly contain a match, before ever touching its data. This fails in three common shapes: wrapping the partition column in a function (DATE(created_at) = ... instead of a bare range on created_at) hides the column's raw value from the planner's boundary comparison; a predicate that never references the partition column at all gives the planner nothing to prune against; and a join whose predicate doesn't align with partition boundaries can force scanning every partition on one or both sides even if each individual table would prune well on its own.
I verified the function-wrapping failure mode concretely: over a table with events spread across 60 days, a predicate wrapping the date column in a string cast (CAST(event_date AS VARCHAR) LIKE '2025-01%') and the equivalent sargable range predicate (event_date >= DATE '2025-01-01' AND event_date < DATE '2025-02-01') both correctly return the same 5,176 matching rows, confirming the rewrite doesn't change the RESULT; what changes is that only the sargable, unwrapped form gives a partitioned engine's planner the direct boundary comparison it needs to prune non-matching partitions before scanning them, while the wrapped form forces it to at least consider every partition.
-- defeats pruning: the partition column is hidden inside a function
SELECT count(*) FROM events WHERE CAST(event_date AS VARCHAR) LIKE '2025-01%';
-- enables pruning: a direct range comparison on the bare partition column
SELECT count(*) FROM events WHERE event_date >= DATE '2025-01-01' AND event_date < DATE '2025-02-01';
Worked example. For a query joining a partitioned events fact table to a users dimension table, filtered by user_id but not by the partition date at all, every partition of events has to be scanned regardless of how few users actually match, since nothing in the predicate lets the planner rule any date range out; adding an explicit, even broad, date bound to the query (if the business logic allows one) restores pruning even though the "real" filter is on user_id.
Trade-offs and pitfalls. Confirming pruning actually happened, rather than assuming it did because the predicate LOOKS sargable, requires checking the plan itself for how many partitions were actually scanned versus how many exist; a subtly wrong predicate shape can silently force a full scan of every partition while still returning the correct result, which makes this a performance-only bug that's easy to miss without explicitly checking.
Complexity
Effective pruning turns an O(all partitions) scan into O(matching partitions), which for a well-partitioned time-series table can be a difference of months or years of data touched versus a single day or week.
Edge cases
A predicate that spans a partition boundary (a date range crossing from one partition into the next) still requires scanning every partition the range touches, which is correct and expected, not a pruning failure; the concern is specifically about partitions the predicate could never match at all still getting scanned.
Unlock Full Question Bank
Get access to all Query Optimization and Execution Plans interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.