BitmapAnd Combine Two Indexes

Watch the planner AND two single-column indexes with BitmapAnd for AND-ed predicates, and why a composite index replaces the merge with one scan.

SqlData Fetching

Code

snippet
-- 两个单列索引:AND 条件下 planner 可以分别取位图,再 BitmapAnd 合并
CREATE INDEX idx_orders_region ON orders (region);
CREATE INDEX idx_orders_status ON orders (status);

EXPLAIN (ANALYZE, COSTS OFF)
SELECT order_id
FROM orders
WHERE region = 'emea'
  AND status = 'open';

-- 高频组合更该直接建复合索引:一次索引扫描出结果,
-- 不需要两次索引扫描加位图合并,也省掉回表再过滤
CREATE INDEX idx_orders_region_status ON orders (region, status);

EXPLAIN (ANALYZE, COSTS OFF)
SELECT order_id
FROM orders
WHERE region = 'emea'
  AND status = 'open';

What the code does

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.

Applying it

Run the statement against the orders table.

Statements that matter

EXPLAIN (ANALYZE, COSTS OFF)
SELECT order_id
FROM orders
WHERE region = 'emea'
AND status = 'open';
CREATE INDEX idx_orders_region_status ON orders (region, status);
CREATE INDEX idx_orders_region ON orders (region);

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
The references are `orders`.