Anlan's Notes

Understanding B-Tree Composite Index Column Order

A common misconception when creating multi-column B-Tree indexes in PostgreSQL is to always place the highest-cardinality column first. In practice, predicate type matters more than raw cardinality.

Equality First, Range Second

Consider a query filtering an events table by tenant and timestamp:

SELECT id, payload
FROM audit_events
WHERE tenant_id = $1
  AND created_at >= NOW() - INTERVAL '7 days'
ORDER BY created_at DESC
LIMIT 50;

Creating the index as (tenant_id, created_at DESC) allows PostgreSQL to jump straight to the matching tenant's slice and walk the leaf pages in reverse order, avoiding a separate sort node entirely.

Validating with EXPLAIN (ANALYZE, BUFFERS)

Always verify index usage with buffer statistics rather than relying on estimated cost alone:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, payload
FROM audit_events
WHERE tenant_id = 42
  AND created_at >= NOW() - INTERVAL '7 days'
ORDER BY created_at DESC
LIMIT 50;

Look for an Index Scan with low shared hit counts and zero Sort nodes in the execution plan.