Learn SQL/Advanced/Query Performance/SQL Composite Index Column Order

SQL Composite Index Column Order

The leftmost-prefix rule — a composite index only helps queries that filter starting from its first column.

What & Why

A composite index is ordered lexicographically, so leading columns control which predicates can narrow its useful range. Column order should follow important query shapes, commonly equality columns before a range or ordering column.

See How It Works

BUSINESS QUESTION

Growth repeatedly filters one event name and then a created_at range.

iduser_idevent_namecreated_atproperties
1001101signup2024-01-15 09:12:00+00{"source":"organic"}
1002101activated2024-01-16 14:25:00+00{"step":"workspace"}
1003102signup2024-02-10 11:08:00+00{"source":"paid"}
1004103report_viewed2024-03-12 16:40:00+00{"report":"retention"}
EXAMPLE QUERY
SELECT
  id,
  user_id,
  event_name,
  created_at
FROM growth.events
WHERE event_name = 'signup'
  AND created_at >= TIMESTAMPTZ '2024-01-01 00:00:00+00'
ORDER BY created_at DESC, id;
RESULT — signups in descending time order
iduser_idevent_namecreated_at
1003102signup2024-02-10 11:08:00+00
1001101signup2024-01-15 09:12:00+00

The fixed predicate returns two signup rows and the requested ordering places event 1003 first.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario