Composite & Covering Indexes

Composite (Multi-column) Index

An index on several columns is sorted by the first column, then the second, and so on, like a phone book sorted by last name then first name.

CREATE INDEX idx_orders_customer_date ON Orders (CustomerID, OrderDate);
Query filters on...Can use the index?
CustomerIDyes
CustomerID and OrderDateyes (best)
OrderDate onlyno, not efficiently (leftmost-prefix rule)

Leftmost Prefix in Action

Uses the index

Filtering on the first column (CustomerID) of the index:

CREATE INDEX idx_orders_customer_date ON Orders (CustomerID, OrderDate);

EXPLAIN QUERY PLAN
SELECT * FROM Orders WHERE CustomerID = 4 AND OrderDate >= '2024-03-01';

Result: 1 row

idparentnotuseddetail
3051SEARCH Orders USING INDEX idx_orders_customer_date (CustomerID=? AND OrderDate>?)

Cannot seek on the index

Filtering only on the second column (OrderDate) of the index:

CREATE INDEX idx_orders_customer_date ON Orders (CustomerID, OrderDate);

EXPLAIN QUERY PLAN
SELECT * FROM Orders WHERE OrderDate >= '2024-03-01';

Result: 1 row

idparentnotuseddetail
20216SCAN Orders

Covering Index

If the index contains every column the query needs, the database answers from the index alone without touching the table.

-- SQL Server / PostgreSQL 11+: extra columns stored in the index leaves
CREATE INDEX idx_orders_customer ON Orders (CustomerID) INCLUDE (Amount);

SELECT CustomerID, SUM(Amount) FROM Orders GROUP BY CustomerID;  -- index-only