Careeroza
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? |
|---|---|
CustomerID | yes |
CustomerID and OrderDate | yes (best) |
OrderDate only | no, 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
| id | parent | notused | detail |
|---|---|---|---|
| 3 | 0 | 51 | SEARCH 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
| id | parent | notused | detail |
|---|---|---|---|
| 2 | 0 | 216 | SCAN 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