Lesson 4 of 5 Developing with Azure Database for PostgreSQL

Indexing PostgreSQL for Query Latency

This lesson explains how the planner uses indexes, the index types and techniques, how to read query plans and how to find missing and unused indexes.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the main scan types.
  • Choose an index type for a query.
  • Interpret signs of trouble in EXPLAIN output.
  • Describe tools for finding missing and unused indexes.

How the planner uses indexes

For each query, PostgreSQL's planner estimates the cost of possible plans and picks the cheapest. Without a suitable index, it reads every row with a sequential scan; with one, it can use an index scan (look up matching rows through the index), an index-only scan (answer entirely from the index) or a bitmap scan (collect matching row locations from one or more indexes, then read them in physical order). The planner relies on table statistics, which ANALYZE and autovacuum maintain, so stale statistics can lead to poor plans.

Indexes speed reads but slow writes and use storage, because every insert and update must also update each index. The aim is therefore a small set of indexes that serve the frequent and latency-sensitive queries, not an index on every column.

Match the pairs

Scan types

Exam skills 2.2.3

Match each plan node with how it reads data.

Log in to try this activity Interactive activities are free with an account.

Index types and techniques

PostgreSQL offers several index types and several ways to shape an index to a query.

  • B-tree (the default) serves equality, ranges, sorting and prefix matches on ordinary types.
  • Multicolumn B-tree indexes serve filters on several columns; put equality columns first and a range or sort column last, such as (tenant_id, updated_at).
  • GIN indexes serve containment queries on jsonb and arrays, and full-text search on tsvector.
  • Partial indexes include only rows that match a predicate, such as WHERE status = 'active', which keeps them small.
  • Expression indexes index a computed value, such as lower(email), which a query must use in the same form.
  • Covering indexes add non-key columns with INCLUDE, enabling index-only scans.
  • BRIN indexes summarize ranges of physically ordered data, such as an append-only event table by time, with very little storage.
CREATE INDEX documents_tenant_updated ON documents (tenant_id, updated_at DESC);
CREATE INDEX documents_attributes ON documents USING gin (attributes jsonb_path_ops);
CREATE INDEX chunks_content_tsv ON chunks USING gin (content_tsv);
CREATE INDEX documents_active ON documents (category) WHERE attributes ->> 'status' = 'active';

CREATE INDEX CONCURRENTLY builds an index without blocking writes on a busy table, at the cost of a slower build that cannot run inside a transaction block.

The following diagram compares two query plans, which shows how a multicolumn index removes a sort.

How a multicolumn index removes the sort. With separate single-column indexes, the planner finds the tenant's rows with a bitmap scan and then sorts 400,000 of them to return 20. An index on (tenant_id, updated_at DESC) lets the planner walk the tenant's rows in date order and stop after 20 rows. Creating it CONCURRENTLY avoids blocking writes.
INCLUDE (title) can make the plan an index-only scan.
Scenario questions

Which index?

Exam skills 2.2.3

Choose the PostgreSQL index that fits each query.

Log in to try this activity Interactive activities are free with an account.

Reading query plans

EXPLAIN shows the plan the planner chose; EXPLAIN (ANALYZE, BUFFERS) also runs the query and reports actual times, row counts and how many pages were read from memory or disk. Reading plans is the reliable way to confirm that an index is used and to find where time goes.

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, title FROM documents
WHERE tenant_id = '6f1c...' AND updated_at > now() - interval '7 days'
ORDER BY updated_at DESC LIMIT 20;

Signs of trouble include a Seq Scan on a large table for a selective filter, a large gap between estimated and actual rows (stale statistics or correlated columns), a Sort node over many rows that an index could have avoided, and many shared read buffers, meaning pages came from disk rather than memory.

Select all that apply

Warning signs in a plan

Exam skills 2.2.3

Identify the warning signs in an <code>EXPLAIN (ANALYZE, BUFFERS)</code> output.

Log in to try this activity Interactive activities are free with an account.

Finding missing and unused indexes

Three sources help tune indexes over time. The pg_stat_statements extension records execution statistics for every normalized query, which reveals the slowest and most frequent statements. pg_stat_user_indexes shows how often each index is scanned, which reveals unused indexes that only slow writes. Flexible server's Query Store captures query performance over time, and its index tuning feature recommends indexes to create or drop based on the captured workload.

  1. Find

    Use pg_stat_statements or Query Store to list the queries with the highest total time.

  2. Explain

    Run EXPLAIN (ANALYZE, BUFFERS) on each to see where time goes.

  3. Index

    Add or adjust an index that matches the filter and sort, preferably CONCURRENTLY.

  4. Verify and prune

    Confirm the new plan, then drop indexes that pg_stat_user_indexes shows are never used.

Worked example

A slow tenant dashboard

A dashboard query lists a tenant's 20 most recently updated documents: WHERE tenant_id = %s ORDER BY updated_at DESC LIMIT 20. The table has 30 million rows and separate single-column indexes on tenant_id and updated_at. EXPLAIN shows a bitmap scan on tenant_id followed by a sort of 400,000 rows.

The query filters by equality on one column and sorts on another, which a multicolumn index on (tenant_id, updated_at DESC) serves directly: the planner walks the index for the tenant in date order and stops after 20 rows, with no sort. Adding INCLUDE (title) could make it an index-only scan. Creating it CONCURRENTLY avoids blocking writes, and the single-column tenant_id index can be dropped afterwards if no other query needs it.

Raising work_mem would make the sort faster but still sort 400,000 rows. A GIN index does not serve ordering. Moving to a larger compute tier would hide the problem at higher cost.

Check yourself

Which column order should a B-tree index use for WHERE tenant_id = %s ORDER BY updated_at DESC?

Show answer

(tenant_id, updated_at DESC): the equality column first, then the sort column, so the planner reads the tenant's rows already in order and can stop at the LIMIT.

Exam Tips

Remember for the exam

  • B-tree for equality, range and sort; GIN for jsonb and full-text; BRIN for ordered append-only data.
  • Multicolumn indexes: equality columns first, then the range or sort column.
  • Confirm index use with EXPLAIN (ANALYZE, BUFFERS).
  • Find slow queries with pg_stat_statements or Query Store; drop unused indexes.