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.
Describe a repeatable methodology for benchmarking a proposed query rewrite (or an index, or a join change) against the current query: how you would capture a fair baseline, control for caching and concurrency, choose metrics, and decide whether an observed improvement is real rather than noise.
Sample Answer
Direct answer. Capture a baseline under realistic, steady-state conditions; run enough warm-up iterations to remove cold-cache noise, and enough repeated measurements to distinguish a real improvement from run-to-run variance; then compare the SAME set of metrics (not just wall-clock time) before and after, under matching concurrency, before calling the result statistically meaningful.
Structured elaboration. A fair baseline needs to reflect the workload's actual steady-state cache behavior, not an artificially cold cache (first run after a restart) or an artificially warm one (running the same query in a tight loop with nothing else happening), since either extreme can make a change look better or worse than it would in production. Run a handful of warm-up iterations before recording anything, then take enough repeated measurements to compute a distribution (not a single number), since a single before/after pair can't distinguish "genuinely faster" from "happened to catch a quiet moment." Collect more than wall-clock time where possible, buffer/IO statistics, CPU time, and (for a rewrite specifically) the plan shape itself, since two runs with similar wall-clock time but very different plan shapes tell you something different than two runs with the same plan shape and different timing. Match concurrency between the before and after runs; testing a rewrite in isolation and comparing it to a baseline captured under real concurrent load (or vice versa) invalidates the comparison.
Worked example. For a proposed query rewrite, a reasonable protocol is: run the original ten times (after three untimed warm-up runs), run the rewrite ten times under the same conditions, and compare the DISTRIBUTIONS of both wall-clock time and a secondary metric like buffer reads, rather than comparing single best-case or single arbitrary runs against each other; if the rewrite's distribution is meaningfully and consistently better across secondary metrics too (not just occasionally faster by chance), that's much stronger evidence than one favorable timing.
Trade-offs and pitfalls. It's tempting to declare victory off a single favorable before/after pair, especially under time pressure; resist that, since a single pair can't distinguish signal from noise, and a change that looked good in one measurement but doesn't hold up under repeated, matched-condition testing is exactly the kind of false confidence that erodes trust in benchmarking as a practice going forward.
Given a short EXPLAIN ANALYZE snippet showing a hash join over two sequential scans with a large row count on one side, identify the single most expensive operator, explain why the planner produced this shape, and propose concrete next steps to validate and fix it.
Sample Answer
Direct answer. Between a hash join and its two sequential scans, the operator responsible for the largest share of actual time, usually the sequential scan feeding the larger side of the hash table, is the single most expensive operator; the fix depends on whether that scan is unavoidable (the query genuinely needs most of the table) or a symptom of a missing index.
Structured elaboration. A hash join builds an in-memory hash table from one input (the "build" side, ideally the smaller one) and probes it with rows from the other (the "probe" side). If both inputs arrive via sequential scans, the optimizer likely concluded that no available index was selective enough to be worth using for either side, given the current statistics. To identify the true bottleneck, compare the actual time and actual row count of each of the two scans and of the hash join node itself: a scan whose actual rows are close to the full table size, on a table where the query's predicate should have been selective, points at a missing or unused index rather than at the join algorithm being wrong.
I ran an illustrative version of exactly this shape (100,000 orders rows hash-joined to 20,000 customers, grouped by region) and confirmed the plan chooses a HASH_JOIN over two SEQ_SCAN nodes when there's no index to make either side selective; that structural shape is the general one this kind of question is testing.
Worked example. If orders has 500,000 rows and the query filters orders.status = 'pending' (a selective predicate matching perhaps 2% of rows) but there's no index on status, the sequential scan reads and filters all 500,000 rows in memory rather than a cheap index lookup returning roughly 10,000. Adding a matching index and re-running the plan would typically change that leaf to an index scan and shrink the rows flowing into the hash join dramatically, which is the concrete next optimization to try rather than trying to force a different join algorithm.
Trade-offs and pitfalls. Forcing a different join algorithm (via a hint or session setting) without first fixing an obviously-missing index just relocates the cost; the hash join was likely the RIGHT choice given the (large) inputs it was handed. Fix the input sizes first, and only reconsider the join algorithm itself if the inputs are already as small as they can reasonably be.
In a columnar cloud warehouse billed by bytes scanned (BigQuery-style), an unpartitioned query over a multi-terabyte table is expensive even though it returns few rows. Estimate the cost impact of the naive query, then propose changes to the table design and the query itself that would meaningfully reduce bytes scanned, with rough before/after numbers.
Sample Answer
Direct answer. A REGEXP_CONTAINS scan with no date filter against a 5 TB unpartitioned table would need to read the entire dataset regardless of how few rows actually match, at an assumed illustrative rate of $5 per TB scanned that's roughly $25 for a single run of this one query (check your actual account's current rate card, since exact per-TB pricing varies by engine, region, and over time); partitioning by date and adding a date filter, or precomputing a boolean flag so the regex only has to run once (at write time) instead of on every read, would each cut that cost roughly in proportion to how much of the 5 TB the rewritten query actually needs to touch.
Structured elaboration. In a bytes-scanned billing model, the cost of a query is essentially independent of how selective its WHERE clause is UNLESS that WHERE clause can be resolved through partition or clustering metadata before reading the underlying data; a regex applied over an unbounded date range with no partition filter forces every byte of every column referenced (here, the payload column across the entire table) to be read and evaluated, regardless of how rare the matching rows actually are. The two effective levers, in order of how directly they attack the actual cost driver: adding a date filter against a date-partitioned version of the table, so the engine can skip entire partitions outside the query's range before reading anything, cutting bytes scanned roughly in proportion to what fraction of the full date range the query actually needs; and precomputing a boolean has_error flag at write/ingestion time (running the expensive regex once, when the row is written, rather than once per query execution), so read-time queries filter on a cheap boolean instead of re-evaluating a regex over the full payload column every single time.
Worked example. If the query genuinely only needs, say, the last 7 days out of roughly two years of retained data, and that 7-day slice is a representative roughly 1% of the table's total date range, partitioning and filtering to just that range would cut bytes scanned from the full 5 TB to roughly 50 GB; at that same assumed $5/TB rate that's a drop from about $25 per run to about $0.25 per run, a rough two-orders-of-magnitude reduction, purely from letting partition pruning skip the other 99% of the date range before reading it at all. Precomputing the boolean flag stacks on top of that: it removes the need to scan and evaluate the (often large) payload text column at query time altogether for the filtering step, leaving only whatever narrower set of columns the query actually needs to return.
Trade-offs and pitfalls. These numbers are illustrative, not audited against this specific engine's real billing edge cases (minimum billable scan sizes, metadata overhead, and caching behavior all vary by system and can shift the exact dollar figure); treat the ROUGH MAGNITUDE of the improvement (an order-of-magnitude-plus reduction from restricting the date range, an additional meaningful reduction from avoiding a full-column regex re-scan) as the reliable takeaway, and verify the exact billed figure against your specific account and query before reporting a precise number to a stakeholder.
Complexity
Bytes scanned drops roughly in proportion to (fraction of the date range actually queried) once partition pruning applies, and drops further once the expensive column (or the expensive regex evaluation over it) is removed from the read path entirely.
Edge cases
A minimum billable scan size or fixed per-query overhead, present in some billing models, means very small, highly-pruned queries don't necessarily scale their cost all the way down to zero linearly; check your specific engine's billing documentation for that floor before promising a stakeholder a cost reduction proportional all the way down.
What is the difference between EXPLAIN and EXPLAIN ANALYZE (or the equivalent in your database of choice)? Explain what information each gives you, when you would rely on EXPLAIN ANALYZE instead of the plan-only form, and any risk of running EXPLAIN ANALYZE against a production system.
Sample Answer
Direct answer. EXPLAIN shows you the plan the optimizer WOULD use and its estimated costs, without running the query. EXPLAIN ANALYZE actually executes the query and reports both the estimates and the real, observed numbers (actual rows, actual time, loop counts) side by side, which is what lets you see where the optimizer's model of the data was wrong.
Structured elaboration. Because EXPLAIN alone doesn't execute anything, it is safe to run against any query, including a write query or one you suspect might be catastrophically slow, and it costs essentially nothing. EXPLAIN ANALYZE actually runs the query end to end (some databases support a dry-run or rollback mode for writes, but by default assume it executes), so it takes as long as the query itself and has the query's real side effects. You reach for EXPLAIN ANALYZE specifically when you need the actual numbers, most commonly to compare "estimated rows" against "actual rows" at each node: a large gap there is one of the single strongest signals that statistics are stale, a predicate is more selective or correlated than the optimizer assumed, or a data distribution has shifted.
Worked example. For a query that filters on created_at in the last 7 days, EXPLAIN might estimate 5,000 matching rows from an index scan. Running EXPLAIN ANALYZE against the same query might show the same index scan node actually returning 500,000 rows. That gap (5,000 estimated vs. 500,000 actual) tells you the optimizer under-costed this branch of the plan and likely chose a downstream join algorithm (say, a nested loop) that only makes sense for the small estimate, not the real volume, which is a very different diagnosis than "the index scan itself is slow."
Trade-offs and pitfalls. Running EXPLAIN ANALYZE against an expensive query in production has a real cost: it fully executes the query, so a query that would normally time out or that writes data is not safe to blindly EXPLAIN ANALYZE without thinking about it first (a SELECT read against a replica, or wrapping a write in an explicit transaction you roll back, are common ways to make this safe). It's also worth remembering that EXPLAIN ANALYZE's timing numbers include the overhead of instrumentation itself, so absolute numbers can be slightly inflated versus a bare run of the query; the RELATIVE comparison between nodes, and between estimated and actual, is what actually matters.
Explain why the optimizer's default per-column statistics can produce badly skewed cardinality estimates when two predicates on separate columns are actually correlated. What are extended (multi-column) statistics, and how would you decide whether creating them actually fixed a bad plan?
Sample Answer
Direct answer. Default per-column statistics assume each column's values are distributed independently of every other column, so when two columns are actually correlated, the optimizer multiplies their individual selectivities together and ends up with an estimate far lower (often wildly so) than the true combined selectivity; extended statistics explicitly capture how those columns co-vary, letting the optimizer estimate the combined predicate's selectivity directly rather than assuming independence.
Structured elaboration. If a city column and a state column are each individually somewhat selective on their own, but every value of city in the data only ever co-occurs with one specific state (a real-world correlation: cities belong to exactly one state), the independence assumption badly overestimates how selective city = X AND state = Y really is: multiplying each column's standalone selectivity together implies the combined predicate is far MORE selective than it actually is, since knowing the city already tells you the state with certainty. Extended (multi-column) statistics record the actual joint distribution across a specified set of correlated columns, so the optimizer can look up (or closely approximate) the real combined selectivity instead of computing a product that assumes independence.
Worked example. Two predicates might each independently match 10% of rows on their own; if they were truly independent, the combined predicate would match roughly 1% (10% times 10%). If the columns are perfectly correlated (every row matching one predicate also matches the other), the true combined match rate is still 10%, not 1%, a ten-fold estimation error that can easily push the optimizer toward an index-heavy plan appropriate for a genuinely rare combination, when the real combination is common enough that a scan-based plan would have been the better choice.
Trade-offs and pitfalls. Extended statistics have to be explicitly created and targeted at the specific column combination that's actually correlated, most engines don't infer correlation automatically and build multi-column statistics for every possible column pair on their own, since that would be prohibitively expensive to maintain; you generally need to notice the estimation error first (via an estimate-actual mismatch on a predicate involving those columns) before you know which specific column combination is worth the investment. Once created, verify the fix by re-checking that predicate's estimated-vs-actual row count, rather than assuming creating the statistics automatically resolved the issue, since the statistics also need to be genuinely representative of the current data to help.
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.