Adding an Index for a Query Pattern

An index can reduce access work for selected queries. It also adds storage and maintenance for writes.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a collection list
  2. Measure against representative data
  3. Match a repeated filter and its order to index keys
  4. Verify the actual production-shaped workload

Trace a collection list

A query repeatedly selects articles by category and time. An index arranged for those fields may help locate matching ordered rows. See composite index prefixes.

Measure against representative data

A very small fixture may scan quickly without an index. Compare expected timings and plans on a relevant distribution before deciding. Reading an execution plan provides the actual chosen path.[1]

Match a repeated filter and its order to index keys

A service regularly retrieves recent reports for one account in descending creation order. An index with the account key followed by time can help access the matching range and produce a useful order, depending on the engine and plan. See ordered range lookup.

Query: one account, newest first
Candidate key begins account_id, then created_at
Include a deterministic result tie-break in the query

Verify the actual production-shaped workload

An index costs storage and maintenance on writes. Plans can still choose a scan when many rows qualify. Inspect the plan on representative data and compare read and write costs.

References

  1. PostgreSQL Global Development Group, Concurrency Control ↩