Sub topic 11
Choosing a PostgreSQL Index Type for Your Workload
Assume you know basic SELECT, WHERE, JOIN, and ORDER BY syntax, can create PostgreSQL tables, and recognize common types such as integer, text, timestamptz, and jsonb. The right index depends on the operators and data shape in your real queries. There is no single “fastest” index for every workload.
Start with the query shape
Choose an index from the work the database must do:
- Use a B-tree for equality, ranges, sorting, and common uniqueness rules.
- Use a GIN index when one row contains many searchable values, such as JSON keys, array elements, or full-text lexemes.
- Use a GiST index for geometric relationships, range overlap, nearest-neighbor ordering, and exclusion constraints.
- Use a BRIN index for very large tables where column values follow the physical row order.
- Use a hash index only for pure equality lookups when B-tree behavior is not needed.
The operator matters as much as the column type. For example, a default B-tree on text can support = and many range operations, but it does not generally make ILIKE '%term%' fast. A GIN index with the gin_trgm_ops operator class can support that substring search.
Compare the main choices
| Index type | Best fit | Important limitation |
|---|---|---|
| B-tree | `=`, ranges, sorting, uniqueness | Poor fit for arbitrary substring searches |
| GIN | `jsonb`, arrays, full-text search | Larger and more expensive to update |
| GiST | Spatial and range operators | Behavior depends on the operator class |
| BRIN | Huge, naturally ordered tables | May return many candidate rows |
| Hash | Equality-only lookups | Cannot support ranges or ordering |
A B-tree is the default choice when no special requirement exists. A multicolumn B-tree can combine filtering and ordering, such as WHERE customer_id = 42 ORDER BY created_at DESC. The order of columns matters. Put columns used for equality filtering before columns used for ranges or ordering when that matches the workload.
GIN stores associations between contained values and rows. It is useful when a jsonb document, array, or text-search document has multiple searchable components. It can consume substantial disk space and make inserts and updates slower.
GiST is a general framework for indexes based on relationships rather than simple sorted values. It supports points, polygons, ranges, and nearest-neighbor queries. It can also enforce rules such as “two reservations must not overlap.” The correct operator class determines which operations are available.
BRIN stores summaries, such as minimum and maximum values, for ranges of table pages. It is extremely small. It works well for append-only event or measurement tables where recorded_at increases with insertion order. If rows are randomly ordered, a BRIN scan may identify many unrelated pages and provide little benefit.
Hash indexes store hash values and support equality. They do not support <, >, BETWEEN, ORDER BY, or prefix searches. In most applications, a B-tree is a more flexible choice for equality too.
Verify the choice with a plan
Create an index for the query you actually run, then inspect the plan:
CREATE TABLE IF NOT EXISTS readings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
recorded_at timestamptz NOT NULL,
sensor_id integer NOT NULL,
value double precision,
payload jsonb NOT NULL DEFAULT '{}'
);
CREATE INDEX IF NOT EXISTS readings_sensor_time_idx
ON readings (sensor_id, recorded_at DESC);
CREATE INDEX IF NOT EXISTS readings_payload_gin_idx
ON readings USING gin (payload);
CREATE INDEX IF NOT EXISTS readings_recorded_brin_idx
ON readings USING brin (recorded_at);
EXPLAIN (ANALYZE, BUFFERS)
SELECT recorded_at, value
FROM readings
WHERE sensor_id = 7
ORDER BY recorded_at DESC
LIMIT 20;Look for an Index Scan, Bitmap Index Scan, or Index Only Scan that uses the intended index. EXPLAIN (ANALYZE, BUFFERS) also reports actual row counts, execution time, and buffer activity. Compare plans before and after adding an index. An index that exists is not automatically useful.
The planner may choose a sequential scan when the table is small, the filter matches a large percentage of rows, or statistics are stale. Run ANALYZE after major data changes. Check whether the query uses the indexed expression exactly. An index on lower(email) cannot help a query that applies a different expression.
Include write and maintenance costs
Every index adds storage and work to INSERT, UPDATE, and DELETE operations. An update to an indexed column may require changes in several index structures. Remove indexes that duplicate other indexes or receive no useful scans, but confirm usage over a representative period first.
For a busy table, build a new index without blocking ordinary writes:
CREATE INDEX CONCURRENTLY readings_sensor_idx
ON readings (sensor_id);CREATE INDEX CONCURRENTLY takes longer and cannot run inside a transaction block, but it reduces disruption. Monitor index usage and size:
SELECT indexrelname,
idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE relname = 'readings'
ORDER BY idx_scan;Treat idx_scan = 0 as a prompt to investigate, not as automatic proof that an index should be deleted. A rarely used index may support an important report or emergency query.
Exercise
A table stores billions of measurements inserted in increasing timestamp order. Queries filter recent timestamps, but writes are continuous. Which index type is a strong first candidate, and why?
Show answer
A BRIN index on the timestamp is a strong first candidate because it stores small summaries for ordered page ranges and adds less write and storage cost than a large B-tree. Confirm its selectivity with EXPLAIN and realistic data.