CodePark/ questions / Indexes
START PRACTICINGPRACTICE
Backend question · Databases & SQL › Indexes

There is a B-tree index on orders (customer_id, created_at). Which query cannot use it efficiently?

WHERE created_at > now() - interval '7 days'

The correct answer is WHERE created_at > now() - interval '7 days'. The index sorts entries by customer_id first. It sorts by created_at only inside each customer. So recent dates are scattered across the whole index. With no condition on the leading column (customer_id), PostgreSQL would have to scan the entire index or the whole table.

The other three queries all filter on
customer_id, the leftmost column of the index. This is called using a leftmost prefix. The query WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10 also gets its rows already in order, so it needs no sort.