Covering index and Index Only Scan
If every needed column is in the index, the table (heap) need not be read. Narrow SELECT * to the needed columns to get an Index Only Scan, and look at its precondition, the Visibility Map.
SQL
Situation
A feature downloads the list of "paid orders since June". The only columns actually used are the order ID and order time, but the query fetches every column with SELECT *.
Tables
| Table | Column | Type | Description |
|---|---|---|---|
orders | ord_id | integer | Order ID |
orders | status, ord_dt | Status, order date and time | |
orders | Others | cust_id, ord_no, amt |
| Index | Columns |
|---|---|
orders_x2 | status, ord_dt, ord_id |
List of paid orders since June
**BEFORE · SELECT ***
SELECT o.*
FROM orders o
WHERE o.status = 'PAID'
AND o.ord_dt >= DATE '2025-06-01'
Check whether the execution plan has a node that reads the table (Heap Scan) and which columns the query uses.
Approach
1. List every column the query uses
If all columns appearing in SELECT, WHERE, and ORDER BY are in one index, there is no reason to read the table.
2. Ask whether every column is really needed
Because of SELECT *, table blocks are read to fetch amt and cust_id, which are not in the index.
3. PostgreSQL needs one more thing
A PostgreSQL index has no information on whether a row is visible to the current transaction (visibility). So the table can be skipped only when the table block is marked "all visible" (Visibility Map).
Explanation
SELECT * → only the needed columns
AFTER · Covering (needed columns only)
SELECT o.ord_id, o.ord_dt
FROM orders o
WHERE o.status = 'PAID'
AND o.ord_dt >= DATE '2025-06-01'
Why it got faster
- Before finds about 16,600 rows with
Bitmap Index Scan, thenBitmap Heap Scanreads the table blocks holding those rows. Buffers about 2,300. - After reads only
orders_x2withIndex Only Scan, becauseord_id,ord_dt, andstatusare all in the index. Buffers about 86. - Check in the Raw tab that
Heap Fetchesis 0. The sandbox table had its Visibility Map filled byVACUUMafter loading, so the table is never checked.
Why this is optimal
- It reads only the index blocks of the needed range. The rows in the range must be read, so it cannot go lower.
Key points
- Covering index: if every column the query uses is in the index, the table is not read.
SELECT *is the most common cause of breaking coverage. - PostgreSQL's precondition: even with
Index Only Scan, recently changed blocks are checked in the table (Heap Fetches). For frequently updated tables the effect depends on VACUUM state. - Since PostgreSQL 11,
INCLUDEcolumns can append columns not used for ordering to an index (a structural change, so this lab does not do it). - DB difference: Oracle applies the same principle with the
INDEX FAST FULL SCANhint, reading the whole index instead of the table (Oracle scenario 15).