Hard java backend

Composite indexes: equality columns first, then range

The 30 second answer

In a B-tree composite index, I put the columns used with equality first and the range column last. Then the database jumps straight to one contiguous slice of the index and reads only matching rows. If the range column comes first, it has to scan the whole range and filter the rest. Column order should follow how the query filters, not the table definition.

In a B-tree index, the leading columns narrow the search. If the equality column comes first, the range condition reads one contiguous slice. If the range column comes first, the index has to scan the whole range and filter. The PostgreSQL docs say conditions on leading columns limit the part of the index that gets scanned.

-- WHERE customer_id = ? AND created_at > ?
CREATE INDEX ON orders (customer_id, created_at);
Sources (2)
  1. Use The Index, Luke: Greater, Less and BETWEEN
  2. PostgreSQL 17: Multicolumn Indexes