Unit content
Composite and covering database indexes
An index can organize more than one column. A composite index orders entries by a sequence of key columns such as
(customer_id, created_at)
rather than by either column independently.
Column order matters
Entries are ordered first by the leading column, then by later columns within equal leading values. An index on (customer_id, created_at) is therefore naturally suited to queries that constrain customer_id and then search or order by created_at.
The reverse access pattern may require a different index.
Selectivity
An index is most useful when it narrows the candidate rows enough to avoid reading a large fraction of the table. Conditions matching almost every row can make an index traversal less attractive than a sequential scan.
Covering indexes
If an index contains every value needed to answer a query, the database may be able to return the result without reading the underlying table rows. Such an index is often called a covering index for that query.
Trade-offs
Adding included or key columns makes an index useful for more queries but increases its size and update cost. Composite-index design therefore follows concrete query patterns rather than a general rule that wider indexes are better.