StoicBuilder

HandbookXI the TabulariumQuery plans

XIthe Tabularium, Model the data

Query plans

1 min readUpdated 28 November

In plain words

A query plan is the step-by-step route the database chooses to answer a query, which explain shows and explain analyze measures, so you can see where the time goes instead of guessing.

Where you see it

Harbor's overdue-invoices report takes two seconds. Running it with explain analyze in the SQL editor shows a tree of steps, each with an estimated and an actual row count, and one step, a sequential scan over every invoice, takes nearly all the time.

Supabase SQL Editordatabase
explain analyzeselect * from invoices where status = 'open' and due_at < now()order by due_at limit 50; Limit (actual time=2140.7..2140.8 rows=50 loops=1) -> Sort (actual time=2140.7..2140.7 rows=50 loops=1) -> Seq Scan on invoices (cost=0.00..51200.00 rows=1200 width=96) (actual time=0.02..2051.3 rows=310450 loops=1) Filter: ((status = 'open'::text) AND (due_at < now()))
Read from the innermost step outwards. Postgres expected 1,200 rows and found 310,450, and the scan took almost all of the two seconds.

What goes wrong

  1. Running explain analyze on a write

    explain analyze really runs the statement, so on a delete or update it deletes or updates. Wrap it in begin and rollback, or use plain explain, which only plans.

    explain analyze delete from invoices where status = 'void';
  2. An index that doesn't match the query

    An index on email doesn't help a query on lower(email), and an index on (team_id, created_at) serves filters on team_id far better than filters on created_at alone. Match the index to the query as written, or index the expression.

  3. Ignoring estimates that are far off

    When the plan expects 1,200 rows and gets 310,000, the database chose its route on bad information. Run analyze on the table to refresh its statistics, then read the plan again.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Run explain (analyze, buffers) on this slow query against a copy with production-sized data, never on a write against production. Paste the plan, point to the step that takes the most time and any row estimate far from the actual count, propose one change, and show the plan again after it.

Quick check

Sign in to earn +10 XP for it

Harbor's sign-in lookup filters on lower(email) and still does a sequential scan, even though users.email has an index. Why?

Got a prompt that touches query plans?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.