Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BIDatabase conceptSeniorCommonTroubleshooting

How would you use EXPLAIN or an execution plan to investigate a slow SQL query?

Answer

Start with the non-executing plan to inspect scan types, join order, estimated rows, filters, sorts and aggregate steps, then use an analyze mode only where executing the statement is safe. Compare estimated with actual row counts and timing because large differences can reveal stale statistics, skew or a predicate the optimizer cannot estimate well. Reproduce with production-like volume and parameters, measure end-to-end latency and I/O, and never treat the plan's abstract cost as elapsed milliseconds.

Strong answer includes

  • reads scans, joins, estimates and filters
  • uses executing analysis safely
  • compares estimates with actual rows and real workload

Practical example

Compare estimated and actual execution
Dialect · PostgreSQLRuntime · static example

Uses PostgreSQL EXPLAIN (ANALYZE, BUFFERS), which must execute on PostgreSQL rather than the SQLite playground.

EXPLAIN (ANALYZE, BUFFERS)
SELECT c.id, SUM(o.amount) AS total
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= DATE '2026-01-01'
GROUP BY c.id
HAVING SUM(o.amount) > 1000;

Inspect scan types, join order, estimated versus actual rows, filters, sorts, timing and buffer activity. Large estimate errors can point to stale statistics, skewed data or predicates the optimizer cannot estimate well.

Expected result: A measured plan whose expensive or misestimated nodes identify where investigation should continue.

#sql#database#explain#query-plan

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery