Difficulty: Advanced
What is a covering index, and how does it let the database answer a query without reading the table?
A covering index is an index that contains every column a query needs, both for filtering and for the output, so the database can answer the query from the index alone. This avoids the extra random reads to the table (the heap in PostgreSQL, the clustered index in MySQL) that a normal index lookup requires. In PostgreSQL this appears as an Index Only Scan, and in MySQL EXPLAIN shows "Using index".
A normal B-tree index stores the indexed key plus a pointer to the row. For a query like:
SELECT order_id, amount_paise FROM orders WHERE user_id = 42 ORDER BY created_at DESC LIMIT 20
an index on user_id finds the matching entries, but then must jump to the table for each one to fetch amount_paise and created_at. Those jumps are random I/O spread across the table, and on a cold cache they dominate the query time. If the index already holds every needed column, those jumps disappear.
CREATE INDEX ON orders (user_id, created_at, amount_paise). All three columns are part of the sorted key.CREATE INDEX ON orders (user_id, created_at) INCLUDE (amount_paise). Supported in PostgreSQL 11+ and SQL Server. Included columns live only in the leaf pages, are not sorted or searchable, and keep the upper levels of the tree smaller.Use key columns for what you filter and sort by; use INCLUDE for columns you only return. INCLUDE is also the way to add payload columns to a UNIQUE index without changing what must be unique.
EXPLAIN ANALYZE shows this as Heap Fetches. Regular VACUUM (autovacuum) keeps this number low.(user_id, created_at) already covers queries that also return the primary key column.INCLUDE syntax; the plan shows an Index Seek with no Key Lookup.SELECT *) so the index no longer covers the query.ORDER BY in INCLUDE, where it cannot provide sort order.VACUUM has set the visibility map.| Regular index | Covering index | |
|---|---|---|
| Index contents | Search key plus row pointer | Search key plus all needed columns |
| Table access | One random read per matching row | None, or only for non-visible pages |
| Plan label (PostgreSQL) | Index Scan | Index Only Scan |
| Cost | Smaller index | Larger index, slower writes |
-- Hot query: latest 20 orders for a user with their amount
CREATE INDEX orders_user_recent_idx
ON orders (user_id, created_at DESC)
INCLUDE (amount_paise, status);
VACUUM (ANALYZE) orders; -- sets the visibility map
EXPLAIN (ANALYZE, BUFFERS)
SELECT created_at, amount_paise, status
FROM orders
WHERE user_id = 42
ORDER BY created_at DESC
LIMIT 20;
Heap Fetches: 0 confirms the query was answered entirely from the index without touching the table.
Covering Index, Index-Only Scan, INCLUDE Clause, Visibility Map, Composite Index