Cost models
Overview
A cost-based optimizer compares estimated work of legal alternatives. PostgreSQL reports startup and total cost in relative planner units; CPU processing, page access, expected cardinality and ordering influence those estimates. A small startup cost can matter for LIMIT. Costs are not elapsed milliseconds, and the optimizer need not enumerate every possible plan.
First example
EXPLAIN QUERY PLAN SELECT id FROM opt_order WHERE amount=420;Observed SQLite result (rows in JSON):
[ [ 2, 0, 0, "SEARCH opt_order USING COVERING INDEX opt_amount (amount=?)" ]]How it works
The first SQLite EQP output uses a covering index for one amount. NOT INDEXED forces a table scan in the second. Both return ID 42 when actually selected; edge tests verify that result. EQP does not report numeric node costs. A simplified educational model could compare scan Nc_row with lookup c_seek + Mc_match; real planners use more factors, including cache and I/O assumptions.
Practical example
EXPLAIN QUERY PLAN SELECT id FROM opt_order NOT INDEXED WHERE amount=420;Observed SQLite result (rows in JSON):
[ [ 2, 0, 0, "SCAN opt_order" ]]Practice and mistakes
Practice: compare the two plans for amount>=10, then run the actual SELECT with ORDER BY id. Hint: change only the predicate. The entire 100-row fixture qualifies. Do not conclude that a forced index is faster from its plan name; measure a representative workload first.
PostgreSQL 17 example — NOT RUN
BEGIN;SET LOCAL statement_timeout='10s';SET LOCAL lock_timeout='2s';CREATE TEMP TABLE opt_customer(id INTEGER PRIMARY KEY, name TEXT NOT NULL);INSERT INTO opt_customer VALUES(1,'Ada'),(2,'Reza'),(3,'Sara'),(4,'Mina');CREATE TEMP TABLE opt_order(id INTEGER PRIMARY KEY,customer_id INTEGER NOT NULL REFERENCES opt_customer(id),amount INTEGER NOT NULL,status TEXT NOT NULL,region TEXT NOT NULL);WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i<100)INSERT INTO opt_order SELECT i,1+(i%3),10*i,CASE WHEN i<=10 THEN 'rare' ELSE 'common' END,CASE WHEN i<=10 THEN 'east' ELSE 'west' END FROM n;CREATE INDEX opt_amount ON opt_order(amount);CREATE INDEX opt_status ON opt_order(status);CREATE INDEX opt_region ON opt_order(region);CREATE INDEX opt_customer_idx ON opt_order(customer_id);CREATE TEMP TABLE opt_line(id INTEGER PRIMARY KEY,order_id INTEGER NOT NULL REFERENCES opt_order(id));INSERT INTO opt_line VALUES(1,1),(2,1),(3,2),(4,42);CREATE INDEX opt_line_order ON opt_line(order_id);ANALYZE opt_order;ANALYZE opt_customer;ANALYZE opt_line;
EXPLAIN SELECT id FROM opt_order WHERE amount=420;SET LOCAL enable_seqscan=off;EXPLAIN SELECT id FROM opt_order WHERE amount=420;ROLLBACK;Expected result, not executed: "Compare costs and access nodes; no plan guaranteed."