Video in progress

What is a covering index, and what is INCLUDE for in PostgreSQL?

A covering index contains all the columns the query needs, so it becomes an Index Only Scan and doesn't go to the heap. INCLUDE stores extra columns only in the index leaf pages: they aren't part of the search key, but they are enough to answer the query.

📖 Answer

A frequently run query:

SELECT status, total FROM orders WHERE customer_id = ?;

An index on customer_id finds the rows, but for status and total it goes to the heap for every row. The covering index:

CREATE INDEX idx_orders_cust_cover
    ON orders (customer_id) INCLUDE (status, total);

Why not (customer_id, status, total)? That works, but:

  • INCLUDE columns aren't stored in the internal pages, so the tree is smaller;
  • you can add extra columns to a unique index while uniqueness stays on the key columns only: UNIQUE (email) INCLUDE (id);
  • an INCLUDE column's type doesn't need a B-tree operator class.

For an Index Only Scan to really skip the heap, the table's pages must be "all-visible" in the visibility map. On a heavily updated table, if VACUUM falls behind, Heap Fetches in the plan comes out large and the benefit is gone.

Be careful: every extra column makes the index bigger and means the index must be updated on every UPDATE. I do this only for very hot queries, the ones near the top of pg_stat_statements.