Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;sql
EXPLAIN (COSTS OFF) SELECT id FROM events WHERE kind = 'refund';text
Seq Scan on events
Filter: (kind = 'refund'::text)sql
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT id FROM events WHERE kind = 'refund';text
Seq Scan on events (actual rows=40 loops=1)
Filter: (kind = 'refund'::text)
Rows Removed by Filter: 1960The ANALYZE output adds actual rows for each node (timing is turned off here so the output is stable). Estimates and actuals that differ by orders of magnitude often explain a bad plan: the planner picked a nested loop for "10 rows" that turned out to be 100,000.
For an UPDATE or DELETE:
text
BEGIN;
EXPLAIN ANALYZE DELETE FROM events WHERE kind = 'refund';
ROLLBACK;BUFFERS adds page reads, which show whether data came from cache. SQLite's EXPLAIN QUERY PLAN is closer to plain EXPLAIN: it shows the plan without running it.
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- EXPLAIN shows estimates without running
- EXPLAIN ANALYZE runs the query and shows actuals
- Compare estimated and actual rows
- Roll back when analyzing data-changing statements
Common mistakes
- Running EXPLAIN ANALYZE on a DELETE outside a transaction
- Reading costs as milliseconds
Follow-ups
- What does ANALYZE (the command) do?
- What does BUFFERS show?
Tips
- Mention the estimate-versus-actual check