Fill the blank
Make SELECT customer_id, total FROM orders WHERE customer_id = $1 eligible for an index-only scan while keeping customer_id the only search key.
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id int,
total numeric
);
CREATE INDEX orders_cust ON orders (customer_id) ____;
SELECT indexdef LIKE '%INCLUDE (total)%'
FROM pg_indexes WHERE indexname = 'orders_cust';Hint 1 of 1
The extra column should be returned, not searched.
Choose an answer, then open Show answer below to check it.
Plan shape checked with EXPLAIN on PostgreSQL 17; page counts are a toy table
Text version
Index on customer_id (Index Scan):
- Root: 301–600
- Inner: 401–500
- Leaf: 434–466
- Table: H4
INCLUDE (total) (Index Only Scan):
- Root: 301–600
- Inner: 401–500
- Leaf: 434–466
- Table: no page
| Scenario | Plan | Index pages | Table pages |
|---|---|---|---|
| Index on customer_id | Index Scan | 3 | 1 |
| INCLUDE (total) | Index Only Scan | 3 | 0 |
Show answer
Answer: A INCLUDE (total)
Correct. total rides along in the leaf entries without becoming part of the key.
An index-only scan needs every column the query reads to be in the index. INCLUDE stores total in the leaf entries without adding it to the key, so the visibility map can let PostgreSQL skip the table.
Why not the others?
- B
WHERE total > 0. A partial index filter; it doesn't add total to the entries. - C
USING hash. Hash indexes can't do index-only scans or carry extra columns. - D
WITH (fillfactor = 90). A storage setting; total still isn't in the index.