Sub topic 3
Choosing key columns versus included columns
This chapter assumes you know B-tree indexes, can write CREATE INDEX, and can read an EXPLAIN plan that shows an Index Only Scan.
Choosing key columns versus included columns
Key columns define the B-tree's sort order. PostgreSQL can search, sort, and enforce uniqueness on them. Included columns are stored only in leaf pages. They cannot be searched or sorted on, but a query can return them without visiting the table.
CREATE INDEX orders_customer_total_idx
ON orders (customer_id) INCLUDE (total);Put a column in the key when WHERE or ORDER BY uses it. Put a column in INCLUDE when it appears only in the SELECT list. INCLUDE requires PostgreSQL 11 or later and works only with B-tree indexes.
The price of covering: size, writes and HOT updates
Each included column is copied into every index entry, so the index grows. A write to an included column also updates the index. An update to any indexed column, including an included one, prevents a heap-only tuple (HOT) update, which normally skips index maintenance. Compare index sizes with pg_relation_size() before and after you add a column.
Troubleshooting: when the planner does not pick an index-only scan
Check these causes in order:
- The query selects a column the index does not hold.
SELECT *often does this. - The visibility map has few all-visible pages. Run
VACUUM (ANALYZE)and checkHeap FetchesinEXPLAIN (ANALYZE, BUFFERS). - The planner expects many matching rows, so a sequential scan looks cheaper. Confirm that statistics are current with
ANALYZE. enable_indexonlyscanis off in the session.
Unique indexes and constraints with INCLUDE
Uniqueness applies only to key columns. This constraint enforces unique id values and stores status and total in the index:
ALTER TABLE orders
ADD CONSTRAINT orders_id_uq UNIQUE (id) INCLUDE (status, total);Partial covering indexes
A partial index holds only rows that match a WHERE predicate. The query must repeat that predicate so the planner can use the index.
CREATE INDEX orders_new_customer_idx
ON orders (customer_id) INCLUDE (total)
WHERE status = 'new';
EXPLAIN
SELECT customer_id, total FROM orders
WHERE status = 'new' AND customer_id = 42;Which index types support index-only scans
B-tree indexes support INCLUDE and index-only scans. GiST and SP-GiST indexes can also return column values for index-only scans, depending on the operator class. GIN, BRIN and hash indexes cannot.
Exercise
Exercise
A query runs SELECT total FROM orders WHERE customer_id = 42 AND status = 'paid'. Which columns go in the key, and which go in INCLUDE?
Show answer
Put customerid and status in the key, because both appear in WHERE. Put total in INCLUDE, because it appears only in SELECT: CREATE INDEX orderspaididx ON orders (customerid, status) INCLUDE (total);