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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- What relations does the SQL touch?
- `orders`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.