Covering Index INCLUDE Index-Only Scan

Add INCLUDE columns to an index so the planner answers from the index alone with an index-only scan and never visits the table heap.

SqlData Fetching

Code

snippet
-- INCLUDE 把列带进索引叶子但不参与键排序:键序仍由 customer_id 决定
CREATE INDEX idx_orders_customer_covering
  ON orders (customer_id) INCLUDE (status, total_cents);

-- 查询只触碰索引列:规划器可走 Index-Only Scan,不回表取行
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, status, SUM(total_cents)
FROM orders
WHERE customer_id = 42
GROUP BY customer_id, status;

-- 对比:count 查询同样只碰索引列,也能吃到 Index-Only Scan
SELECT COUNT(*) FROM orders WHERE customer_id = 42;

-- visibility map 覆盖前仍需回表核对可见性;
-- VACUUM 之后 index-only scan 才能真正零回表
VACUUM (ANALYZE) orders;

How it works

Several statements share this file — SELECT / CREATE / EXPLAIN, with orders among the objects involved.

Concretely, the SQL combines: a WHERE clause narrowing which rows one statement affects; COUNT, SUM aggregation; a GROUP BY that collapses matching rows into one output row per group.

Applying it

The orders table is the working surface here.

Statements that matter

EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, status, SUM(total_cents)
FROM orders
WHERE customer_id = 42
GROUP BY customer_id, status;
SELECT COUNT(*) FROM orders WHERE customer_id = 42;
CREATE INDEX idx_orders_customer_covering
ON orders (customer_id) INCLUDE (status, total_cents);

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`orders`.