Lesson 1 of 13 · 12m
Your SQL Is a Specification, Not a Plan
Postgres parses, rewrites, and cost-optimizes your SQL against pg_statistic — stale statistics are the real cause of most suddenly-slow plans.
When you send SELECT * FROM orders WHERE status = 'pending' to Postgres, nothing in the engine reads top to bottom the way you typed it. The text goes through a pipeline: parser, analyzer, rewriter, planner, executor. The parser turns the string into a parse tree. The analyzer resolves orders to a real relation OID and status to a real column type. The rewriter expands views and applies rules. The planner generates candidate plan trees — seq scan plus filter, index scan plus filter, different join orders — and scores each with a cost model. Then the executor runs the cheapest one. You described a result set. Postgres decided how to build it.
The wrong model: SQL runs in the order you wrote it
The mental model most people carry is that SQL is a script. WHERE happens after FROM, SELECT happens last, and the engine filters rows in the sequence the clauses appear. Under that model, people do things that don't help: reorder WHERE conditions to "filter early," split one query into three "to give the database less work," or add a redundant WHERE clause to a view "so it runs faster."
None of it moves the needle, because the planner doesn't owe your clause order anything. It rearranges predicates, pushes them down into scans, reorders joins, and substitutes the view definition for the view name before it ever looks at cost. Two syntactically different queries routinely compile to byte-identical plans.
What the planner actually optimizes over
The cost model runs on statistics stored in pg_statistic. ANALYZE populates them: for each column it samples up to default_statistics_target * 300 rows — 30,000 rows at the default target of 100 — and records n_distinct, most_common_vals with frequencies, histogram_bounds, and correlation. When the planner sees WHERE status = 'pending' it doesn't guess; it looks up pending in the MCV list and estimates how many rows survive.
This is where the real-world failures live. After a bulk load, pg_statistic describes yesterday's table. The planner estimates one row, picks a nested loop join, and then executes that loop 2 million times because the table actually grew overnight. The query didn't get slower because of the data; it got slower because the statistics went stale. This is why autovacuum also runs auto-ANALYZE, and why every serious ETL job ends a load with an explicit ANALYZE staging_table before the swap.
Join order is the other silent giant. Up to geqo_threshold FROM-clause items (default 12) the planner searches join orders exhaustively-ish with dynamic programming; past that it switches to a genetic algorithm. A six-table join has 720 possible orders, and the wrong one is often the difference between hashing 200 rows and hashing 20 million.
Prove it to yourself
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, c.email
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending' AND o.created_at > now() - interval '7 days';Read the output bottom-up. Every node reports cost=startup..total in cost units, rows as the planner's estimate, and after ANALYZE, actual time and rows as measured reality. Compare estimated rows to actual rows at each node. When they're off by 10x or more at the bottom of the tree, everything above that node was chosen based on a lie — that's your fix, not the query.
What to actually do
- Run
ANALYZEon any table you bulk-load before you point production queries at it. Since Postgres 13, inserts do count towardautovacuum_analyze_scale_factor(default 0.1), so a bulkCREATE TABLE ... ASdoes get auto-analyzed — on the autovacuum daemon's schedule (autovacuum_naptime, default one minute), not yours. Queries that hit the table in that window plan on stats for zero rows. The explicitANALYZEcloses the window; the daemon is the backstop, not the plan. - When estimates are wrong on a skewed column, raise the sample:
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000;thenANALYZE orders. - Stop rewriting SQL to "help" the planner. Write the result set you mean; spend your effort on the statistics the planner uses to get there.
- When the same query must behave the same way every run — a pipeline query, a report — run
EXPLAIN ANALYZEonce against realistic data and save it. The first time the plan changes, you'll know the statistics changed, not the SQL.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
PostgreSQL Fixed 52 CVEs in One Release. The Upgrade Is the Easy Part.
PostgreSQL 18.7, 17.12, 16.16, 15.20 and 14.25 fix 52 security vulnerabilities, almost twice August's record of 28. The binary swap took under a second in my test. The post-update steps are where the work is, and one of them makes some indexes several times bigger.
What PostgreSQL 15 Changed
A new version of the popular open-source database PostgreSQL is now available, offering performance improvements over PostgreSQL 14 and new functions and capabilities for managing workloads in local and distributed deployments. Released on October 13 by the PostgreSQL Global Development Group,…
PHP API Performance: N+1 Queries, cURL, and Connection Pools
A PHP API case study: fixing an N+1 query, twenty serial cURL calls, missing connection pooling, and stats recalculated on every request with Redis caching.