Sub topic 1
What an Index Does and Why the Planner May Ignore It
Prerequisites
This chapter assumes you can:
- Write
SELECTqueries withWHERE,JOIN, andORDER BY. - Create tables and insert rows in PostgreSQL.
- Recognize common column types such as
integer,text,timestamptz, andjsonb.
You do not need to read query plans fluently yet. The next chapter covers EXPLAIN (ANALYZE, BUFFERS) in detail. Here we only look at the top node of each plan to see which scan type the planner chose.
The problem an index solves
A PostgreSQL table is stored as a heap: a collection of 8 kB pages that hold rows in no particular order. Suppose you run this query:
SELECT * FROM orders WHERE customer_id = 42;With no other structure, PostgreSQL must read every page of orders and test every row. This is a sequential scan. Its cost grows with the size of the table, even if only 20 rows match.
An index is a separate data structure that maps column values to the physical locations of matching rows. Instead of reading the whole table, PostgreSQL looks up 42 in the index, gets a short list of row locations, and reads only the heap pages that contain those rows.
What an index stores
Each index entry holds two things:
- A key: the indexed value, such as
42. For some index types the key is a derived value, such as a word extracted from a document. - A TID (tuple identifier): a pair of values, the heap page number and the row's position within that page. It tells PostgreSQL where the row lives.
The index is a different object from the table. It has its own files on disk and takes its own space. It is also kept in sync with the table. Every INSERT adds entries, and every UPDATE that creates a new row version may add entries as well.
PostgreSQL has several index types: B-tree, hash, GiST, GIN, and BRIN. They differ in how they organize keys and which operators they can answer. The rest of this tutorial covers each one. Every type follows the same pattern of key in, TIDs out.
How a query uses an index
When the planner decides an index is worthwhile, it picks one of three scan methods.
| Scan type | What happens | Typical use |
|---|---|---|
| Index Scan | Walks the index and fetches each matching heap row one at a time, in index order. | Few matching rows, or when index order satisfies `ORDER BY`. |
| Bitmap Index Scan plus Bitmap Heap Scan | Collects all matching TIDs into an in-memory bitmap, then reads the heap pages in physical order. | A moderate number of rows, or combining several indexes with `AND` and `OR`. |
| Index Only Scan | Answers the query from the index alone, without visiting the heap. | All needed columns are in the index, and the pages are marked all-visible. |
Index Only Scan has one catch. PostgreSQL uses MVCC (multiversion concurrency control), so an index entry does not say whether the row is visible to your transaction. The visibility map records which heap pages contain only rows visible to everyone. For those pages, PostgreSQL skips the heap visit. For other pages, it must still check the heap. A table that is updated heavily and rarely vacuumed gets less benefit from index-only scans.
The bitmap scan exists because random heap access is expensive. If 5,000 matching rows are scattered across 4,000 pages, fetching them one by one would revisit pages in a jumping pattern. The bitmap sorts the work by page number, so each page is read once.
How the planner chooses
PostgreSQL does not apply a rule such as "always use an index if one exists." The planner estimates the cost of each possible plan and runs the cheapest. The cost is an abstract number built from these parts:
- The number of pages it expects to read, weighted by
seq_page_cost(default 1.0) for sequential reads andrandom_page_cost(default 4.0) for random reads. - The number of rows it expects to process, weighted by
cpu_tuple_cost,cpu_index_tuple_cost, andcpu_operator_cost.
To estimate how many rows a condition matches, the planner uses statistics collected by ANALYZE and stored in pg_statistic (readable through the pg_stats view). They include the fraction of nulls, the number of distinct values, the most common values with their frequencies, and a histogram of the remaining values. The fraction of rows a condition matches is its selectivity.
The default random_page_cost of 4.0 assumes spinning disks. On SSDs, many installations lower it to between 1.1 and 2.0. A lower value makes index plans look cheaper. Change it only after you have measured that your storage behaves that way.
A worked example
Create a table with a million rows. Most orders are closed, and about 5 percent are open.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total numeric(10,2),
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO orders (customer_id, status, total, created_at)
SELECT (random() * 9999)::bigint + 1,
CASE WHEN random() < 0.95 THEN 'closed' ELSE 'open' END,
(random() * 500)::numeric(10,2),
now() - random() * interval '365 days'
FROM generate_series(1, 1000000);
ANALYZE orders;Ask for the plan of a lookup on customer_id. At this point the only index is the primary key on id, so the planner has nothing useful.
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;The top node is Seq Scan on orders. Each customer has about 100 rows, which is 0.01 percent of the table, but PostgreSQL cannot find them without reading everything.
Now add an index and refresh the statistics.
CREATE INDEX orders_customer_idx ON orders (customer_id);
ANALYZE orders;
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;The plan now starts with Bitmap Heap Scan on orders, fed by a Bitmap Index Scan on orders_customer_idx. For about 100 scattered rows the planner may also choose a plain Index Scan. Either result means the index was used. The exact choice depends on your data layout and settings.
Why the planner may ignore an index
Sometimes an index exists and the planner still chooses a sequential scan. The reason is almost always one of the cases below.
The condition matches too much of the table
Add an index on status, then query for the common value.
CREATE INDEX orders_status_idx ON orders (status);
ANALYZE orders;
EXPLAIN SELECT * FROM orders WHERE status = 'closed';About 95 percent of rows match. Using the index would mean reading nearly every heap page anyway, plus the index pages, so a sequential scan is cheaper. The planner is right to ignore the index here. Now try the rare value.
EXPLAIN SELECT * FROM orders WHERE status = 'open';Here 5 percent of rows match. The planner will likely choose a bitmap scan, because the index now saves work. The same index is used for one value and ignored for another. The planner decides per query, from the value's frequency in pg_stats.
A low-selectivity column like status is rarely worth a plain index. Later chapters show partial indexes, which index only the rare rows.
The table is small
If a table fits in a few pages, reading all of it is as cheap as reading an index page plus a heap page. A sequential scan on a 50-row table is correct. Do not conclude from a toy table that an index is broken.
The query does not match the index
The index is useful only if the query contains a condition the index can answer. Common mismatches:
- A function or cast on the column.
WHERE customer_id::text = '42'cannot use an index oncustomer_id, because the index storesbigintvalues, not text. Rewrite the condition asWHERE customer_id = 42, or create an expression index on the computed value. - An operator the index does not support. A default B-tree supports
<,<=,=,>=, and>. It cannot answerjsonbcontainment (@>) orILIKE '%smith%'. Those need other index types or operator classes, covered in later chapters. - The wrong leading column in a multicolumn index. An index on
(customer_id, created_at)helps queries that filter oncustomer_id. It generally does not help a query that filters only oncreated_at. - A leading wildcard.
LIKE '%abc'cannot use an ordinary B-tree, because the index is sorted from the start of the string.
Check the first of these yourself.
EXPLAIN SELECT * FROM orders WHERE customer_id::text = '42';The plan shows a Seq Scan with a filter on the cast value, even though orders_customer_idx exists.
Statistics are stale
The planner trusts pg_stats. After a bulk load or a large delete, the statistics may describe a table that no longer exists, and the planner may predict 10 rows where there are 500,000. Autovacuum normally runs ANALYZE in the background, but it can lag behind a large change. Running ANALYZE tablename; by hand is cheap and a good first step when a plan looks wrong.
The index does not provide the needed order, or a LIMIT changes the math
Indexes can also remove a sort. A query with ORDER BY created_at LIMIT 10 may be cheapest by walking an index on created_at and stopping after 10 rows. If no index matches the ORDER BY, the planner must sort all matching rows. The opposite can also happen. If a LIMIT query's filter is rarer than the planner thinks, an ordered index scan can end up reading far more than expected.
Cost settings do not match your hardware
If random_page_cost is too high for your storage, index plans look more expensive than they are. Compare the actual runtime of both plans before you change it.
Testing whether the index could have been used
To check that the index is capable of serving a query, you can discourage sequential scans for one transaction.
BEGIN;
SET LOCAL enable_seqscan = off;
EXPLAIN SELECT * FROM orders WHERE status = 'closed';
ROLLBACK;enable_seqscan = off does not forbid sequential scans. It adds a large penalty to their cost, so the planner uses them only if no alternative exists. If the plan now uses the index, the index matches the query and the planner simply judged it more expensive. If the plan still shows a sequential scan, the index cannot answer the query at all.
Compare the two plans by running them with EXPLAIN ANALYZE, which the next chapter explains. An index the planner ignores is often an index you do not need. Each one costs space and slows writes, as a later chapter shows.
A troubleshooting checklist
When an expected index is not used, work through these questions in order:
- Is there a condition in the query that the index's type and operator class can answer, with no cast or function wrapped around the column?
- For a multicolumn index, does the query filter on the leading column?
- Are the statistics current? Run
ANALYZEand check the plan again. - How selective is the condition? Look at
most_common_valsandmost_common_freqsinpg_statsfor the column. - Does the plan with
SET LOCAL enable_seqscan = offuse the index, and is it actually faster?
Exercise
A table events has 2 million rows and an index on kind. 90 percent of rows have kind = 'page_view'. The query SELECT * FROM events WHERE kind = 'page_view' shows a sequential scan, even though the index exists. Is something wrong? What would you check, and which values of kind would you expect the index to help with?
Show answer
Nothing is wrong. The condition matches about 90 percent of the table, so reading the index and then nearly every heap page costs more than scanning the heap once. The planner learned this from the frequency of 'pageview' in pgstats. You can confirm with SELECT most_common_vals, most_common_freqs FROM pg_stats WHERE tablename = 'events' AND attname = 'kind';. The index should help for rare values of kind, where the condition matches a small fraction of rows, and the planner will likely pick an index or bitmap scan for those.
Exercise
You have CREATE INDEX ON orders (customer_id); and run SELECT * FROM orders WHERE customer_id::text = '42';. The plan is a sequential scan. Give the reason and two ways to fix it.
Show answer
The index stores bigint values, and the query applies a cast to the column, so the planner cannot match the condition to the index. Fix 1: compare in the column's own type, as in WHERE customer_id = 42. Fix 2: if the cast is genuinely needed, create an expression index on the same expression, CREATE INDEX ON orders ((customer_id::text));, and then run ANALYZE orders;.