Sub topic 1
What an Index Does and Why the Planner May Ignore It
Prerequisites
You should know basic SQL, including SELECT, WHERE, JOIN, and ORDER BY. You should also be able to create PostgreSQL tables and insert rows. This chapter assumes familiarity with common types such as integer, text, timestamptz, and jsonb.
How an Index Avoids a Full Table Scan
An index is a separate data structure that helps PostgreSQL find table rows. Without an index, PostgreSQL may read every row and test the WHERE condition. This is a sequential scan, often called a full table scan.
A B-tree index stores values in sorted order with references to table rows. For example, an index on customer_id lets PostgreSQL navigate directly to entries for customer 42 instead of checking every order.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
total numeric(10,2),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_id_idx
ON orders (customer_id);
SELECT id, total
FROM orders
WHERE customer_id = 42;The index does not replace the table. PostgreSQL usually uses an index to find row locations, then reads the matching rows from the table. This is called an index scan.
The planner may combine an index with another operation. For example, it can use an index to find rows and then sort them, or use a bitmap index scan to collect many matching row locations before reading the table efficiently.
Why the Planner May Ignore an Index
PostgreSQL's planner estimates the cost of possible execution plans. It uses table statistics, estimated row counts, and operation costs. The planner chooses the plan with the lowest estimated cost, not necessarily the plan that mentions an index.
A sequential scan can be cheaper when:
- The table is small.
- The query matches a large percentage of rows.
- The table or index pages are already cached differently than expected.
- The condition is not selective enough.
- Statistics are stale or inaccurate.
- The query applies a function that the existing index does not support.
- A type conversion prevents the expected comparison.
- The query needs many table columns, making random table reads expensive.
For example, finding one customer in a large orders table may benefit from an index. Finding nearly every order probably does not. Reading the table sequentially can be faster than visiting many scattered index entries and then fetching the same rows.
An index also cannot help every expression. An index on email does not normally support this query efficiently:
SELECT id
FROM users
WHERE lower(email) = '[email protected]';The indexed value is email, but the query compares lower(email). An expression index on lower(email) would match this query shape.
Reading an Execution Plan
Use EXPLAIN to inspect the plan without running the query. Use EXPLAIN ANALYZE to run the query and report actual timing and row counts. BUFFERS shows page activity, which helps identify expensive reads.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;Look for these important parts:
| Plan detail | Meaning |
|---|---|
| `Index Scan` | PostgreSQL follows an index to find rows |
| `Seq Scan` | PostgreSQL reads the table sequentially |
| `Bitmap Index Scan` | PostgreSQL finds many matching row locations through an index |
| `actual time` | Measured execution time for a plan node |
| `rows` | Number of rows produced by a plan node |
| `Buffers` | Pages read from or found in shared memory |
Compare estimated rows with actual rows. A large difference can cause a poor plan. Run ANALYZE orders; to refresh statistics after substantial data changes.
A Practical Investigation
When a query is slow, start with its actual workload rather than adding indexes immediately:
- Run
EXPLAIN (ANALYZE, BUFFERS)on a representative query. - Check whether the planner estimates the row count accurately.
- Check whether the condition, sort, or join matches an existing index.
- Refresh statistics with
ANALYZEif the table changed substantially. - Test an index in a controlled environment.
- Compare execution time and write overhead before keeping it.
Do not disable sequential scans as a permanent fix. Temporarily changing planner settings can help diagnose a cost estimate problem, but it does not correct the underlying statistics or query design.
Exercise
A query filters a large table by status, but the plan uses a sequential scan. The query returns 85% of the table's rows. Is the missing index automatically a problem?
Show answer
No. Reading most of the table sequentially may cost less than using an index and fetching nearly every matching row. Compare actual execution time and buffer usage before deciding.