Subscribe

Postgres index design: B-tree, composite, partial and covering indexes

Hands-on Postgres 18 index design on a 2 million row table: when a B-tree helps, which column goes first in a composite index, partial indexes for soft deletes, INCLUDE for index-only scans, and what extra indexes cost on every insert.

Postgres index design: B-tree, composite, partial and covering indexes

Most slow queries I have looked at had the same fix: the right index. But "add an index" is where the advice usually stops, and the details are where it goes wrong. Which columns, in which order, should it cover deleted rows, should it carry extra columns?

In this blog we will look at index design in Postgres by running real queries against a table with 2 million rows. It is an intermediate post. You should be able to read an EXPLAIN ANALYZE plan; if not, start with my older post on EXPLAIN and query plans and come back. This is also the first post of a small "Postgres in production" series.

I used Postgres 18.7 (the postgres:18-alpine image) on my laptop. Every plan below is pasted from that run.

The test tables

The tables come from shorty, the URL shortener from designing a URL shortener. Shorty's real links table is smaller, so I added an owner_id, a deleted_at for soft deletes and a clicks table with one row per click. That is what a bigger shorty would need anyway.

docker run -d --name pg18 -e POSTGRES_PASSWORD=secret postgres:18-alpine
docker exec -i pg18 psql -U postgres -c "CREATE DATABASE shorty"
CREATE TABLE links (
    id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    code       text        NOT NULL,
    url        text        NOT NULL,
    owner_id   bigint      NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now(),
    deleted_at timestamptz
);

CREATE TABLE clicks (
    id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    link_id    bigint      NOT NULL REFERENCES links(id),
    clicked_at timestamptz NOT NULL,
    country    text        NOT NULL
);

-- 200k links from 5k owners, about 1 in 10 soft deleted
INSERT INTO links (code, url, owner_id, created_at, deleted_at)
SELECT substr(md5(g::text), 1, 10),
       'https://example.com/page/' || g,
       (random() * 4999)::int + 1,
       now() - (random() * interval '365 days'),
       CASE WHEN random() < 0.1 THEN now() - (random() * interval '30 days') END
FROM generate_series(1, 200000) AS g;

-- 2M clicks over the last 90 days
INSERT INTO clicks (link_id, clicked_at, country)
SELECT (random() * 199999)::int + 1,
       now() - (random() * interval '90 days'),
       (ARRAY['IN','US','GB','DE','SG'])[(random() * 4)::int + 1]
FROM generate_series(1, 2000000);

VACUUM ANALYZE links;
VACUUM ANALYZE clicks;

My first try used 8 characters of the md5 for the code. With 200k rows that gives a few duplicates, and the unique index later would fail. Ten characters was enough.

A plain B-tree

The redirect is shorty's hottest query: code in, url out. Without an index Postgres reads the whole table.

EXPLAIN ANALYZE SELECT url FROM links WHERE code = 'c4ca4238a0';
 Seq Scan on links  (cost=0.00..4981.00 rows=1 width=31) (actual time=0.016..7.345 rows=1.00 loops=1)
   Filter: (code = 'c4ca4238a0'::text)
   Rows Removed by Filter: 199999
   Buffers: shared hit=2481
 Execution Time: 7.367 ms

Two things are new if you last looked at plans on an older version. Postgres 18 shows buffers with plain EXPLAIN ANALYZE, no BUFFERS option needed, and row counts are printed with two decimals. Anyway, the index:

CREATE UNIQUE INDEX links_code_key ON links (code);
EXPLAIN ANALYZE SELECT url FROM links WHERE code = 'c4ca4238a0';
 Index Scan using links_code_key on links  (cost=0.42..8.44 rows=1 width=31) (actual time=0.019..0.020 rows=1.00 loops=1)
   Index Cond: (code = 'c4ca4238a0'::text)
   Index Searches: 1
   Buffers: shared hit=1 read=3
 Execution Time: 0.044 ms

2481 pages down to 4. That is the whole idea of a B-tree.

Then I tried a prefix search, WHERE code LIKE 'c4ca%', expecting the same index to help. It did not, it went back to a seq scan. The database collation is en_US.utf8, and a normal B-tree on a non-C collation can't serve LIKE prefixes. You need an index with text_pattern_ops:

CREATE INDEX links_code_prefix ON links (code text_pattern_ops);
EXPLAIN ANALYZE SELECT url FROM links WHERE code LIKE 'c4ca%';
 Index Scan using links_code_prefix on links  (cost=0.42..8.44 rows=20 width=31) (actual time=0.015..0.019 rows=3.00 loops=1)
   Index Cond: ((code ~>=~ 'c4ca'::text) AND (code ~<~ 'c4cb'::text))
   Filter: (code ~~ 'c4ca%'::text)

Same story with lower(code) = ...: an index on code does nothing for it. You'd need an expression index on lower(code). The index has to match what the query actually asks.

Composite indexes and column order

The stats page asks for one link's clicks in the last 7 days, newest first. Without an index it was a parallel seq scan over 2 million rows, 24 ms. I first made the index the way a lot of people would, time first:

CREATE INDEX clicks_at_link ON clicks (clicked_at, link_id);
 Index Scan Backward using clicks_at_link on clicks  (cost=0.43..3929.26 rows=1 width=11) (actual time=0.592..2.530 rows=1.00 loops=1)
   Index Cond: ((clicked_at > (now() - '7 days'::interval)) AND (link_id = 4242))
   Buffers: shared hit=16 read=599 written=213
 Execution Time: 2.542 ms

It used the index and it is faster than the seq scan, so it looks fine at first glance. But look at the buffers: 615 pages to return one row. Postgres walked every entry from last 7 days and checked link_id on each. Now the other order:

DROP INDEX clicks_at_link;
CREATE INDEX clicks_link_at ON clicks (link_id, clicked_at);
 Index Scan Backward using clicks_link_at on clicks  (cost=0.43..8.45 rows=1 width=11) (actual time=0.015..0.015 rows=1.00 loops=1)
   Index Cond: ((link_id = 4242) AND (clicked_at > (now() - '7 days'::interval)))
   Buffers: shared hit=1 read=3
 Execution Time: 0.024 ms

4 pages. The rule I use: columns compared with = go first, the range or ORDER BY column goes last. The index then jumps to link_id = 4242 and reads a short, already sorted run. No sort step either.

The leading column also works on its own, so WHERE link_id = 4242 gets an index-only scan from this same index. A query only on clicked_at normally can't use it. Postgres 18 added skip scan, which helps when the leading column has few distinct values. With country first (5 values) and a filter only on time:

CREATE INDEX clicks_country_at ON clicks (country, clicked_at);
EXPLAIN ANALYZE SELECT count(*) FROM clicks WHERE clicked_at > now() - interval '1 hour';
   ->  Index Only Scan using clicks_country_at on clicks  (cost=0.43..41.58 rows=858 width=0) (actual time=0.046..0.134 rows=918.00 loops=1)
         Index Cond: (clicked_at > (now() - '01:00:00'::interval))
         Heap Fetches: 0
         Index Searches: 6

Index Searches: 6 is one dive per country plus one. With link_id first (200k values) the planner didn't bother and did a seq scan, which is right. I wouldn't design for skip scan, it's a nice bonus.

Partial indexes for soft deletes

The dashboard lists an owner's live links. Almost every query in an app with soft deletes has deleted_at IS NULL in it, so the index can leave dead rows out:

CREATE INDEX links_owner_active ON links (owner_id, created_at DESC)
    WHERE deleted_at IS NULL;

EXPLAIN ANALYZE
SELECT id, code, url FROM links
WHERE owner_id = 77 AND deleted_at IS NULL
ORDER BY created_at DESC LIMIT 20;
 Limit  (cost=0.42..82.99 rows=20 width=58) (actual time=0.025..0.065 rows=20.00 loops=1)
   ->  Index Scan using links_owner_active on links  (cost=0.42..149.05 rows=36 width=58) (actual time=0.024..0.063 rows=20.00 loops=1)
         Index Cond: (owner_id = 77)
 Execution Time: 0.071 ms

From 15.8 ms to 0.07 ms. To be honest the size saving was small here, 5576 kB against 6184 kB for the full index, because only 10% of my rows are deleted. On a table where most rows are soft deleted or "done" (think job queues) a partial index can be a fraction of the size.

The catch: a query without deleted_at IS NULL can't use it. I dropped the full index and ran the dashboard query without the filter and it went straight back to a parallel seq scan. Your ORM has to add that condition every time.

Partial indexes also give you a nice trick for unique codes. A deleted link's code can be reused if uniqueness only covers live rows:

DROP INDEX links_code_key;
CREATE UNIQUE INDEX links_code_live ON links (code) WHERE deleted_at IS NULL;

Covering indexes with INCLUDE

An index scan finds the row in the index, then goes to the table (the heap) for the other columns. If the index has every column the query needs, Postgres can do an index-only scan. INCLUDE adds columns to the leaf pages without making them part of the key:

CREATE UNIQUE INDEX links_code_live_inc ON links (code) INCLUDE (url)
    WHERE deleted_at IS NULL;
DROP INDEX links_code_live;
 Index Only Scan using links_code_live_inc on links  (cost=0.42..4.44 rows=1 width=31) (actual time=0.029..0.030 rows=1.00 loops=1)
   Index Cond: (code = 'c4ca4238a0'::text)
   Heap Fetches: 0

For a single row lookup it read the same 4 pages as before, so don't expect miracles there. It pays off on ranges. Then I updated 4000 rows and ran range query:

UPDATE links SET url = url WHERE id % 50 = 0;
EXPLAIN ANALYZE SELECT url FROM links WHERE code BETWEEN 'c4' AND 'c5' AND deleted_at IS NULL;
 Index Only Scan using links_code_live_inc on links  (cost=0.42..90.44 rows=701 width=31) (actual time=0.039..1.392 rows=710.00 loops=1)
   Heap Fetches: 728
   Buffers: shared hit=738

728 heap fetches for 710 rows. The "index only" scan went to the table anyway. Postgres can skip the heap only for pages marked all-visible in the visibility map, and my update cleared that. After a VACUUM links it was Heap Fetches: 0 and 10 buffers. So covering indexes depend on vacuum keeping up, on a busy table autovacuum settings matter as much as the index.

The cost of too many indexes

Every index is updated on every insert, and on updates that touch an indexed column. I made two empty copies of clicks: one with the primary key plus one index, one with the primary key plus six. Then inserted 500k rows into each.

INSERT 0 500000
Time: 1064.359 ms (00:01.064)     -- 2 indexes
INSERT 0 500000
Time: 4542.802 ms (00:04.543)     -- 7 indexes

   relname   | table_size | index_size
-------------+------------+------------
 clicks_few  | 29 MB      | 30 MB
 clicks_many | 29 MB      | 98 MB

Four times slower, and the indexes are more than three times the size of the table. That's the bill for "just add one more index".

To find indexes nobody uses, ask pg_stat_user_indexes:

SELECT relname, indexrelname, idx_scan,
       pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0 AND schemaname = 'public'
ORDER BY pg_relation_size(indexrelid) DESC;

Be careful with the result. On my run clicks_pkey showed up with zero scans and 43 MB. You still can't drop it, it enforces the primary key. Also these counters are per server, so a read replica has its own numbers, and they start from zero after a stats reset. PgHero shows the same unused and duplicate index lists in a page if you'd rather click than query.

How I pick an index now

I start from the query, never from the table. I write the WHERE and ORDER BY, put the equality columns first and the range or sort column last, add a WHERE to the index if every query has the same filter, and use INCLUDE only for the few hot queries that read one or two extra columns. Then I check the plan, and I check Buffers, not just the time, because on a laptop with a warm cache the times lie a bit.

All the SQL above runs top to bottom in a fresh container, then docker rm -f pg18 cleans up. Next in this series is transactions and isolation levels, with two psql sessions fighting over the same row.