Sub topic 12
What Indexes Cost
Prerequisites and the basic trade-off
This chapter assumes you know basic SELECT, WHERE, ORDER BY, and CREATE INDEX syntax. You should also know that an index stores a separate, ordered structure that helps PostgreSQL find table rows without scanning the whole table.
An index trades write cost and storage space for faster reads. Every index should support a real query or a data rule. An index that no important query uses still makes the table more expensive to change.
Cost during writes
When PostgreSQL inserts a row, it must add an entry to every index on the table. When it updates an indexed column, PostgreSQL must create an appropriate new index entry. When it deletes a row, PostgreSQL must mark index entries for cleanup.
For example, these indexes all add work to changes on orders:
CREATE INDEX orders_customer_idx
ON orders (customer_id);
CREATE INDEX orders_status_created_idx
ON orders (status, created_at);
CREATE INDEX orders_total_idx
ON orders (total_cents);An insert into orders now updates three B-tree structures as well as the table itself. More indexes can reduce write throughput and generate more write-ahead log, or WAL, activity. WAL is PostgreSQL's durable record of changes used for crash recovery and replication.
Updates can cost more than inserts when they change indexed values. An update to total_cents must maintain orders_total_idx. An update to an unrelated column may still create a new table version because PostgreSQL uses multiversion concurrency control. Old index entries and table versions are later cleaned up by vacuum.
Storage and maintenance cost
Indexes consume disk space and memory. A larger index needs more pages, so useful portions may be less likely to stay in the shared buffer cache. Index size depends on factors such as row count, key width, included columns, and how often updates create dead entries.
You can inspect relation sizes with PostgreSQL's size functions:
SELECT
pg_size_pretty(pg_relation_size('orders')) AS table_size,
pg_size_pretty(pg_indexes_size('orders')) AS indexes_size;A multicolumn index can replace several narrower indexes for a particular workload, but it cannot serve every column order equally well. Avoid adding overlapping indexes without checking their use.
A partial index often costs less than a full index because it stores only matching rows:
CREATE INDEX orders_pending_created_idx
ON orders (created_at)
WHERE status = 'pending';This index is especially useful when pending orders are a small, frequently queried part of the table. It still adds work when a row enters or leaves the pending set, and PostgreSQL must evaluate the predicate when maintaining the index.
Expression indexes also have maintenance cost. PostgreSQL computes the expression when creating or changing an indexed row:
CREATE INDEX users_lower_email_idx
ON users (lower(email));An INCLUDE column can enable an index-only scan, but included data makes the index larger. An index-only scan also depends on visibility information being current. It is not guaranteed merely because all selected columns appear in the index.
Measuring whether an index pays off
Use EXPLAIN (ANALYZE, BUFFERS) on representative queries:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_cents
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;EXPLAIN shows the planner's chosen path. ANALYZE runs the query and reports actual timing and row counts. BUFFERS reports page activity. Run this in a safe environment first for expensive or write-producing statements.
The planner may choose a sequential scan even when an index exists. That can be correct when the query returns a large fraction of the table, the table is small, or statistics are stale. An unused index is a candidate for review, not automatic proof that it should be removed.
Choosing the smallest useful design
Start with the query's filtering, joining, and sorting needs. Prefer a narrow index when it solves the query. Use a partial index when the workload repeatedly targets a stable subset. Use an expression index only when queries use the same expression. Add INCLUDE columns when measured index-only scans justify the extra size.
Exercise
A table has one million orders, but only two percent have status pending. A frequent query finds old pending orders. Why might a partial index be better than a full index on created_at?
Show answer
It stores entries for only the pending rows, reducing index size and maintenance work while supporting that frequent query.