Sub topic 1
The problem: scanning every row
Prerequisites
This chapter assumes you have the following:
- Basic SQL:
SELECT,WHERE,ORDER BY, andJOIN. - Familiarity with tables, rows, columns, and primary keys.
- A working idea of Big-O notation, especially linear (O(n)) versus logarithmic (O(log n)) growth.
- Optionally, a PostgreSQL 11+ instance. The examples use PostgreSQL syntax, but the idea applies to every relational database.
Why start with the slow path
Indexes are an answer to a specific problem, so you need to see the problem first. A database that has no useful index for your query falls back on the only strategy that always works: read every row and check it. This chapter explains what that costs, how to see it happen, and when it is acceptable.
What a full table scan does
A table has no inherent order that helps you find a value. If you ask for WHERE customer_id = 42, the database cannot know where those rows are, or even whether any exist, until it has looked at all of them. A full table scan (PostgreSQL calls it a sequential scan, or "Seq Scan") reads the table from start to finish. It tests the WHERE condition against each row and keeps the rows that match.
flowchart TDThat fence is not valid for the platform. The real diagram follows.
Two details matter for what follows.
- The cost does not depend on how many rows match. A query that returns one row and a query that returns none both read the whole table. The work is set by table size, not by result size.
- The unit of I/O is the page, not the row. Databases store rows in fixed-size blocks called pages (8 KB in PostgreSQL by default). The database reads whole pages, then examines the rows inside them. A scan therefore costs roughly "number of pages" in I/O plus "number of rows" in CPU work for evaluating the condition.
Cost grows linearly
If the table doubles, a full scan takes about twice as long. That is O(n) behavior. The table below assumes about 125 rows per 8 KB page, which is realistic for narrow rows like the orders table used in this tutorial.
| Rows in table | Approx. pages | Approx. data read per scan |
|---|---|---|
| 10,000 | 80 | 640 KB |
| 1,000,000 | 8,000 | 64 MB |
| 100,000,000 | 800,000 | 6.4 GB |
At 10,000 rows the scan is instant. At 100 million rows, a single lookup moves gigabytes through the storage layer and the CPU. If the table is not already in memory, it also waits on disk. Now multiply by concurrency. If 200 requests per second each trigger a scan, the database is doing 200 table reads per second to answer questions whose answers are a handful of rows each.
The result is a typical production failure. A query that was fast in development, with a few thousand rows, becomes slow as the data grows, and nothing in the query changed.
Seeing it happen
Create the orders table from this tutorial and fill it with a million synthetic rows. generate_series produces the numbers 1 to 1,000,000. Each customer ID appears 20 times (50,000 customers).
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total_cents integer NOT NULL
);
INSERT INTO orders (id, customer_id, status, created_at, total_cents)
SELECT g,
(g % 50000) + 1,
CASE WHEN g % 10 = 0 THEN 'open' ELSE 'closed' END,
timestamptz '2026-01-01' + g * interval '30 seconds',
(random() * 10000)::int
FROM generate_series(1, 1000000) AS g;
ANALYZE orders;ANALYZE refreshes the statistics the planner uses. Without it, the planner may work from stale numbers. Check how big the table is on disk:
SELECT pg_size_pretty(pg_relation_size('orders')) AS table_size,
relpages,
reltuples::bigint AS estimated_rows
FROM pg_class
WHERE relname = 'orders';Expect a size in the tens of megabytes. The exact figure depends on your version and settings. Now run a lookup on a column with no index. The primary key index covers only id, so customer_id has nothing to use.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;The output looks like this. Treat the numbers as illustrative, because yours will differ with hardware, version, and cache state.
Gather (cost=1000.00..13000.00 rows=20 width=36)
(actual time=0.9..45.0 rows=20 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared hit=8000
-> Parallel Seq Scan on orders (cost=0.00..12000.00 rows=8 width=36)
(actual time=5.0..40.0 rows=7 loops=3)
Filter: (customer_id = 42)
Rows Removed by Filter: 333326
Buffers: shared hit=8000
Planning Time: 0.1 ms
Execution Time: 46.0 msRead these lines in order:
Seq Scan(hereParallel Seq Scan, where several worker processes each scan a share of the pages) is the full table scan.Filter: (customer_id = 42)is the condition applied to every row. It is a filter, not a way to jump to rows.Rows Removed by Filtershows the waste. Each of the three processes (two workers plus the leader) discarded about 333,000 rows to return a handful. In total, about a million rows were examined to return 20.Buffers: shared hit=8000is the number of pages touched. Here they all came from the cache. On a cold cache these would beread=entries, meaning disk I/O.
The ratio of rows examined to rows returned is the number to watch. Here it is 50,000 to 1.
When a scan is the right answer
A full scan is not always a defect. The planner picks it deliberately in several cases.
- Small tables. If a table fits in a few pages, reading it directly is as cheap as consulting any lookup structure. Indexes on tiny tables add write cost for no read benefit.
- Queries that return a large share of the table.
WHERE status = 'closed'matches 90% of the rows in the example above. Reading the table in order is cheaper than jumping around to fetch nearly every page. The next chapters on selectivity explain why. - Analytical queries. Reports that aggregate over most of a table need every row anyway.
LIMITwith early matches. A scan can stop as soon as it has enough rows.SELECT * FROM orders WHERE status = 'open' LIMIT 5finishes quickly because open orders are common and appear early. The same scan on a rare value can still read the entire table.
Sequential reads are also the cheapest kind of I/O on both spinning disks and SSDs, since the database can read ahead in large chunks. This is why "always avoid Seq Scan" is bad advice. The real problem is a scan that reads a large table to return a small fraction of its rows, repeatedly.
Mitigations that are not indexes
Before indexes, people try other fixes. Each has limits.
- More memory. A cached table scans faster than an uncached one, but the CPU still evaluates every row. The cost stays linear.
- Parallel scans. As in the plan above, workers split the pages. This divides the time by a small factor. It does not change how the cost grows, and it consumes CPU that other queries need.
- Faster hardware. It shifts the point where the problem appears. It does not remove it.
All three reduce the constant factor. An index changes the growth rate. It lets the database find matching rows in O(log n) steps instead of O(n), which is what the following chapters build up.
Key takeaways
- Without a usable index, the database examines every row, whatever the result size.
- Scan cost is proportional to table size, measured in pages read and rows tested.
- In
EXPLAINoutput,Seq Scan,Filter, and a largeRows Removed by Filteridentify the pattern. - A scan is correct for small tables and for queries that need most of the rows.
- Caching and parallelism lower the cost per row but leave it linear.
Exercise
A table has 50,000,000 rows at about 125 rows per 8 KB page. A query SELECT * FROM t WHERE code = 'X7' has no index on code and returns 3 rows. Roughly how many pages does a sequential scan read, and how many rows does it test? Would the answer change if the query returned 3,000 rows?
Show answer
About 400,000 pages (50,000,000 / 125), which is roughly 3.2 GB, and all 50,000,000 rows are tested against the condition. The answer would not change for 3,000 returned rows. A scan reads the whole table regardless of how many rows match. Only the work of collecting and sending the result grows slightly.
Exercise
You run EXPLAIN (ANALYZE) on a query and see Seq Scan on payments, Rows Removed by Filter: 9,999,990, and rows=10. Is this a problem if the table has 10,000,000 rows and the query runs once a night? What if it runs 500 times per second from a web page?
Show answer
A nightly run is likely fine, since the scan takes a bounded amount of time and has no user waiting. At 500 times per second it is a serious problem. Each run examines about 10 million rows to return 10, so the database does 5 billion row tests per second of load and will saturate CPU and I/O. The query is a candidate for an index. The scan cost is the same in both cases, but how often the query runs decides whether it matters.