Reading preferences
Concept

Indexes and Their Trade-offs

Understand when an index can help and what it costs to maintain.

database, postgresql, sql, indexes, btree, performance

A second path to a row

An index is an additional structure that can help PostgreSQL locate rows. Think of a book index: it points toward relevant places, but consulting it is not always cheaper than reading a short book from the beginning. PostgreSQL chooses between access paths using estimated costs, statistics, and the query; an index is an opportunity, not a promise.

SQL illustration

In the same disposable PostgreSQL session, first run the fictional books setup:

CREATE INDEX books_pages_idx ON books (pages);
SELECT id, title, pages FROM books
WHERE pages >= 120
ORDER BY id;

Prepared result — not live execution:

idtitlepages
1Kite120
3Tide200
4Fern120

The default PostgreSQL index is a B-tree, which can support comparisons such as >=. Oak's NULL does not pass this condition. The four-row table is so small that a sequential scan may be preferable; the result does not tell us which access path was used.

See the reasoning

Follow the example one step at a time

Compare possible access paths for the page-count condition. This is a prepared teaching demonstration, not live code execution.

Start with the condition

books.pages >= 120

Kite 120  Oak NULL  Tide 200  Fern 120

Three rows satisfy the condition; the NULL comparison is unknown.

Choose for a workload

B-tree indexes support common equality, range, and some ordering operations. Hash indexes support equality; GIN can support suitable queries on composite values such as JSONB; GiST and BRIN serve other specialised workloads. Operator classes and predicates matter. Multicolumn index order affects which conditions and orderings it can support. An index may enable an index-only scan when required values and visibility information permit it, not in every case.

Indexes occupy space and add maintenance on writes. Measure a representative workload and inspect plans before and after a change. Avoid assuming that an index improves every query, that one type suits every operator, or that a small sample predicts production performance.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What can an index help PostgreSQL find?
2. Does creating an index guarantee that a query will use it?
3. What is one cost of an additional index?
4. Which index type commonly supports equality and range comparisons?

References and further reading