Menu▾

Get the column order right on a composite index

bookings is filtered constantly by route, and about half of those queries add a second filter on status. Nothing ever filters by status alone. Create one composite index that serves both query shapes — filtering on route alone, and filtering on route AND status together — as efficiently as a single index can.

Column order in a composite index isn't arbitrary: an index on (a, b) can be used for a query that filters on a alone, but is far less useful for a query that filters on b alone. Put the columns in the order that matches how these queries actually filter.

Schema

▸bookings
idINT
routeTEXT
statusTEXT
fareNUMERIC

Example input

Why

A composite (multi-column) B-tree index is physically sorted by its first column, then by its second column within each value of the first — the phone-book analogy in the hints is literally how the index is laid out on disk. (route, status) lets Postgres jump straight to a route, then optionally narrow further by status within that route, so it serves both "route = X" and "route = X AND status = Y". Flip it to (status, route) and the same index can serve "status = Y AND route = X" just as well, but "route = X" alone would have to scan across every status value looking for that route — index columns after the first are only useful once every column before them is also constrained.

↑ Read the question

Keep going

Company names are trademarks of their respective owners, used here only to describe practice material. mahir_data is not affiliated with, endorsed by, or sponsored by any company named on this site. Terms.