Sub topic 1
The Problem: Scanning Every Row
A database can answer a query by reading every row in a table and testing its WHERE condition. This is a full table scan, also called a sequential scan. It is simple and often efficient for small tables. As a table grows, however, the database must do more work even when the query needs only one row.
Prerequisites
You should know basic SQL, including SELECT, WHERE, and ORDER BY. You should also understand tables, rows, columns, primary keys, and the difference between linear and logarithmic work.
How a full table scan works
Suppose an application needs the order belonging to customer 42. Without a suitable access path, the database checks each row:
- Read a row from the table.
- Compare its
customer_idwith42. - Return matching rows.
- Continue until the table ends.
If the table contains one million rows, the database may inspect one million rows to find one match. The work grows linearly with the number of rows, or O(n).
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total_cents integer NOT NULL
);
INSERT INTO orders (id, customer_id, status, total_cents)
VALUES
(1, 10, 'paid', 2500),
(2, 42, 'open', 1800),
(3, 91, 'paid', 4200);
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;The plan will commonly contain Seq Scan on orders. Seq means sequential: PostgreSQL reads the table in physical order and evaluates the condition for each row.
A sequential scan is not automatically bad. Reading most rows is often faster than jumping through an index and then fetching many separate table pages. The planner compares these choices using estimated costs.
Why growth matters
A scan has several costs:
- I/O: The database may need to read table pages from storage.
- CPU: It evaluates the predicate for every row.
- Memory pressure: Reading pages can displace other useful pages from the cache.
- Concurrency: A long scan consumes resources while other queries compete for them.
Modern databases cache frequently used pages, so a scan may be faster when the table is already in memory. Caching reduces storage reads, but it does not remove the need to inspect rows or spend CPU time on the predicate.
An index provides another route to matching rows. Instead of checking the table from beginning to end, the database can search an ordered structure for the requested value. The next chapter explains what that structure contains and how it works.
Exercise
A query returns 10 rows from a table containing 20 million rows. Why might a sequential scan be expensive, and when could it still be the right plan?
Show answer
It may read and test millions of rows, consuming I/O and CPU. It can still be appropriate when most table pages are already cached, when no useful index exists, or when the planner estimates that reading many rows is cheaper than using an index.