Sequential and index scans
Overview
A scan supplies rows to a physical plan. A sequential scan reads a relation in its storage order; an index access path finds keys and may fetch corresponding table rows. Neither guarantees output order without ORDER BY.
First example
EXPLAIN QUERY PLAN SELECT id FROM po_order NOT INDEXED WHERE amount=150;Observed SQLite result (rows in JSON):
[ [ 2, 0, 0, "SCAN po_order" ]]How it works
The six-order fixture has an index on amount. The first plan intentionally uses NOT INDEXED and scans the table. The second uses a covering index to find amount 150; both queries without EXPLAIN return ID 2. A scan can win when most rows qualify or random table lookups are expensive. In PostgreSQL a bitmap index scan collects candidate locations, followed by a bitmap heap scan that visits relevant pages and may recheck conditions. Index-only scans can still need heap visibility checks. A Limit node can stop a demand-driven child early; it does not guarantee little work if a blocking sort precedes it. Inspect actual plans rather than assuming all index access is faster.
Practical example
EXPLAIN QUERY PLAN SELECT id FROM po_order WHERE amount=150;Observed SQLite result (rows in JSON):
[ [ 2, 0, 0, "SEARCH po_order USING COVERING INDEX po_amount (amount=?)" ]]Practice and mistakes
Practice: compare plans and ordered results for amount >= 100 with and without NOT INDEXED. Hint 1: remove EXPLAIN to check results. Hint 2: order by id; expect IDs 1, 2, 3, 6. Do not infer timing from EQP.
PostgreSQL 17 example — NOT RUN
BEGIN;SET LOCAL statement_timeout='10s';SET LOCAL lock_timeout='2s';CREATE TEMP TABLE po_customer(id INTEGER PRIMARY KEY, name TEXT NOT NULL);INSERT INTO po_customer VALUES(1,'Ada'),(2,'Reza'),(3,'Sara'),(4,'Mina');CREATE TEMP TABLE po_order(id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES po_customer(id), amount INTEGER NOT NULL CHECK(amount>=0));INSERT INTO po_order VALUES(1,1,100),(2,1,150),(3,2,250),(4,2,50),(5,2,50),(6,4,100);CREATE INDEX po_customer_amount ON po_order(customer_id,amount);CREATE INDEX po_amount ON po_order(amount);
ANALYZE po_order;ANALYZE po_customer;EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) SELECT id FROM po_order WHERE amount=150;SET LOCAL enable_seqscan=off;EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) SELECT id FROM po_order WHERE amount=150;ROLLBACK;Expected result, not executed: "Compare access nodes; result ID 2; no plan guaranteed."