Sphere
Log in Join
☆ 3

Why did my Postgres index stop being used after adding ORDER BY created_at DESC?

Postgres 16, table with about 4 million rows. A query filtering on tenant_id used the index on that column until I added ORDER BY created_at DESC LIMIT 20. Now it does a sequential scan and sort. There is a separate index on created_at. Why did the planner change its mind?

⚑ Report

4 replies

☆ 3
F ferretpixel42 ·2026-11-12#1

With two separate indexes Postgres would have to scan every matching tenant row and then sort. It usually decides that is worse than a sequential scan. You want one composite index that matches both the filter and the order.

⚑ Report
☆ 0
T tiny7 ·2026-11-14#2

So (tenant_id, created_at DESC) rather than two indexes. Would the direction matter if I also query ascending somewhere else?

⚑ Report
☆ 0
S Samir ·2026-11-15#3

A btree can be scanned backwards, so direction usually does not matter for a two-column index. Create (tenant_id, created_at) and check with EXPLAIN ANALYZE.

⚑ Report
☆ 0
T tiny7 ·2026-11-17#4

Added the composite index, ANALYZE, and the plan switched to an index scan. Down from 1.8 s to 9 ms.

⚑ Report
Log in to reply.