← 中文资源

简体中文版本

BitmapOr 合并两个索引

OR 条件两侧可各自走单列索引,规划器用 BitmapOr 把两张位图合并成一个节点;与 AND 不同,复合索引救不了 OR,小表仍可能退回顺序扫描。

阅读英文原文

实现说明

实际执行的是 SELECT / CREATE / EXPLAIN——messages 是涉及的对象。 用到的 SQL 构件:WHERE 按条件筛出这条语句真正触碰的行。

常见问题

说出这个文件涉及的表。

messages。

核心语句

EXPLAIN (COSTS OFF)
SELECT message_id
FROM messages
WHERE sender = 'bob' OR priority = 'high';
CREATE INDEX idx_messages_priority ON messages (priority);
CREATE INDEX idx_messages_sender ON messages (sender);

代码示例

-- Each side of the OR hits a different single-column index: the planner can merge both bitmaps with BitmapOr
CREATE INDEX idx_messages_sender ON messages (sender);
CREATE INDEX idx_messages_priority ON messages (priority);

EXPLAIN (COSTS OFF)
SELECT message_id
FROM messages
WHERE sender = 'bob' OR priority = 'high';

-- Plan shape (large table): a top-level BitmapOr with two Bitmap Index Scans beneath it,
-- one per single-column index above; the bitmaps merge by row union before a single heap pass,
-- and a row matching both sides is fetched from the heap exactly once
-- Unlike AND, a composite index cannot rescue OR - a single btree cannot serve two columns'
-- independent equality conditions at once, so there is no "build a composite and skip the merge" equivalent;
-- on small tables the planner may still seq-scan; trust the actual EXPLAIN output