Before continuing: This entry is part of the indexes guide. If you are new to the topic, start with INDEX.
Example
A composite index holds two or more columns in a defined order. For example, an index on (customer_id, date) can suit queries that first narrow down by customer_id and then use date to narrow further or sort the results.
CREATE INDEX idx_orders_customer_date
ON orders (customer_id, date);The order is not decorative. In B-tree indexes, and in SQLite's model for multi-column indexes, the leading columns play a special role in locating ranges of the index.
How it is used
Picture a filing cabinet sorted first by customer and, within each customer, by date. Finding a customer's orders and going through them in date order fits that layout. Searching for a date alone is a different question, because the cabinet is still organised by customer first.
Design from the queries: do not ask “which columns are important?” but “which filters, joins and sorts often appear together?”.
Differences and trade-offs
Why order matters
| Index | What it suits |
|---|---|
(customer_id, date) | Queries focused on one or more customers, then by date. |
(date, customer_id) | Queries focused first on a period, then on the customer. |
PostgreSQL documents that a multi-column B-tree is most efficient when there are conditions on the leading columns. SQLite explains the same idea by showing that a multi-column index can be reused for lookups on its leftmost prefix.
Avoid redundant indexes
More indexes do not automatically mean better performance. Each index takes space and must be maintained whenever data changes. If a longer index already covers the prefix of another, check whether the shorter one still adds real value before keeping both. The final decision depends on the engine and on your queries.
Usa EXPLAIN and representative measurements to check the plan, rather than assuming an index will be used just because it exists.
Avoid this confusion
Ordering columns by gut feeling
The order should reflect real query patterns. An index designed for customer_id + date should not be reversed just because “date looks more selective” without checking the plan and the workload.
Creating an index for every possible combination
That increases maintenance and storage. Prioritise the important queries and avoid combinations with no measurable need.
Promising that the index will always be used
The optimiser may prefer another access path. Whether an index helps depends on statistics, cardinality, size and estimated costs.