Sphere
Log in Join
☆ 16

composite index column order matters, query still slow

Postgres 15. I have a composite index on (a, b) but a query filtering only on b is slow and EXPLAIN shows no index use:

Seq Scan on t (cost=0.00..5000.00 rows=1 width=32) (actual time=0.01..45.0 rows=1 loops=1)
Filter: (b = 99)

I thought having b in the index was enough. Why isn't it used? Been going in circles on this for a day.

⚑ Report

4 replies

☆ 0
H hex ·2026-10-14#1

A composite index on (a, b) is a B-tree ordered by a first, then b. Postgres can't use it efficiently to look up b alone because it would have to scan every distinct a. The leading column matters. If you query by b often, add a separate index on (b), or reorder to (b, a) if b is always the more selective predicate.

⚑ Report
☆ 0
C cardboard ·2026-10-20#2

So the leftmost column rule. If I query by both a and b, the (a, b) index works, right? And would (b, a) also help queries that filter on a alone? I will report back once I have tested it.

⚑ Report
☆ 0
I inode ·2026-10-25#3

If you filter on both, (a, b) works well. A (b, a) index helps queries on b alone and on b+a, but not a alone. You might need two indexes depending on your access patterns. Check pg_stat_user_indexes to see which indexes are actually used before adding more.

⚑ Report
☆ 0
S soggy ·2026-10-26#4

Added a dedicated index on (b) since that's the common single-column filter. EXPLAIN now shows an index scan, 0.04ms. I also checked pg_stat_user_indexes and dropped one unused index I found. Column order in composite indexes is not obvious until you hit this.

⚑ Report
Log in to reply.