← 中文资源

简体中文版本

如何用 INCLUDE 实现覆盖索引

用覆盖索引与 INCLUDE 把查询变成仅索引扫描,并理解可见性映射仍会强制访问堆的情况。

阅读英文原文

引言

包含查询所需一切的索引能不触表地回答它,把扫描加回表变成仅索引扫描。因每行避免随机堆访问,在大表上快得多。PostgreSQL 用 INCLUDE 直接支持:它把负载列加到索引而不使之成为搜索键的一部分,从而获得覆盖收益又不加宽索引排序的键。微妙之处是仅索引扫描仍依赖可见性映射,因此未被好好 vacuum 的表收益低于预期。

覆盖对复合

复合索引把其所有列作为键的一部分,按整个键字典序排列索引。覆盖索引仅从索引回答查询。两者目标不同:键列参与排序且可被搜索;包含列存于叶页但用于排序或搜索。

INCLUDE 让你两者兼得:在键列上搜索,并把负载作为包含列携带,使叶页已有所选数据。键保持窄,索引排序高效,负载搭便车供仅索引扫描。

为何仅索引扫描更快

普通索引扫描在索引中找到匹配行,再从堆读每行以取投影列。堆访问是随机的,在大表上常是主要成本。仅索引扫描从索引叶页读一切,叶页物理且顺序,完全避免堆。

查询返回很多行、投影列少、且堆访问会分散时收益最大。返回一行的查询差异可忽略;返回数千行时可能是毫秒与秒之别。

可见性映射的注意事项

仅索引扫描只有在索引标记该行可见时才避免堆,这依赖可见性映射。映射说明哪些页全可见且已知不含死元组,使仅凭索引项可信。若映射未更新,执行器仍须查堆以确认行可见性,扫描退化为普通索引扫描。

这就是 vacuum 对覆盖索引重要的原因:被好好 vacuum 的表有新鲜可见性映射,仅索引扫描真正跳过堆。重写之后、vacuum 跟上之前,同一查询做更多堆取。把 vacuum 策略纳入计划,并看 EXPLAIN 中的堆取计数。

选择包含什么

恰好包含目标查询投影的列,不多不少。每个包含列加宽叶页并增大索引,耗存储且拖慢扫描。携带无查询需要的列的覆盖索引只是更大的索引。

当多个查询共享键时,若投影重叠一个覆盖索引可服务它们;否则可能需多个覆盖索引,或对较少见的查询接受堆取。取舍是索引大小与写成本对堆取成本,应从实测计划决定。

写成本与索引维护

每个索引在其列写时更新,带包含列的覆盖索引在任何被覆盖列变化时更新,即使该列不在键中。包含频繁更新的列如状态或计数器使索引维护昂贵。

宁可包含稳定列、避免包含热列,或拆分覆盖索引使频繁变化的数据不被携带。测量写放大:加速读却拖慢写的索引在写密集表上可能净亏。

读计划确认

计划是仲裁者。找 Index Only Scan 与低堆取计数;若见普通 Index Scan,则查询投影了索引未覆盖的列,或规划器另有选择。比较加 INCLUDE 前后的计划。

有时即便能,规划器也不会选覆盖索引,因其成本估计偏好别的路径。若是,检查统计是否新鲜、投影是否真与索引匹配;若估计错,那是要修的统计问题,而非强制计划的理由。

常见陷阱与小结

不要包含查询不投影的列。不要忘记仅索引扫描依赖新鲜可见性映射,因此 vacuum 是设计的一部分。不要不权衡写成本就包含热列。不要期望规划器选估计偏了的覆盖索引;修统计。也不要为堆取微不足道的单行查找建覆盖索引。

带 INCLUDE 的覆盖索引从索引叶页而非堆回答查询,把分散随机 IO 变成索引的顺序扫描。恰好包含投影列、保持键窄、vacuum 使可见性映射让扫描跳过堆、并权衡写成本。用 EXPLAIN 确认扫描真正仅索引,同一查询在大表上就便宜得多。

代码示例

-- Key: (customer_id, created_at). Payload: (id, amount, status).
-- Search/sort on the key; answer the query from the leaf pages.
CREATE INDEX CONCURRENTLY idx_orders_cover
  ON orders (customer_id, created_at) INCLUDE (id, amount, status);

-- A query projecting only covered columns can be an index-only scan:
SELECT id, amount, status
FROM orders
WHERE customer_id = $1 AND created_at >= $2
ORDER BY created_at;
# normal index scan: index lookup -> heap fetch per row (random IO)
# index-only scan:   index lookup -> read projected cols from leaf (sequential)
# gain is large when:
[ ] many rows returned
[ ] few columns projected
[ ] heap access would be scattered
# gain is small for single-row lookups
-- Confirm the scan is truly index-only: "Heap Fetches" should be low.
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, amount, status FROM orders
WHERE customer_id = 42 AND created_at >= '2026-10-01'
ORDER BY created_at;
--   Index Only Scan using idx_orders_cover
--     Heap Fetches: 0        <- map fresh; heap skipped entirely
--     Heap Fetches: 12000    <- map stale; vacuum to fix
# include only what the query projects
[ ] list the columns the target query selects
[ ] include those, nothing else
[ ] if two queries share a key and overlap in projection, one index serves both
[ ] otherwise weigh a second covering index vs a heap fetch for the rarer query
# each included column grows the index and its write cost
# a covering index is a write-time cost
[ ] included column changes => index updated on every update
[ ] including a hot column (status, counter) => expensive writes
[ ] prefer stable payload columns in INCLUDE
[ ] on write-heavy tables, weigh read gain vs write amplification
# measure: index size, writes/sec, and the read queries it accelerates
# plan tells
Index Only Scan  + Heap Fetches: 0/低   -> covering works
Index Only Scan  + Heap Fetches: 高     -> stale visibility map (vacuum)
Index Scan (not only)                    -> projection not fully covered
Seq Scan                                 -> planner didn't choose it; check stats