Partial Index Serves Its Predicate

A partial index only helps queries whose WHERE clause implies the index predicate, so the planning output decides whether it gets used.

SqlData Integrity

Code

snippet
-- 90% 的行已退款:在整表上建索引浪费空间
CREATE INDEX idx_refunds_open
    ON refunds (created_at)
    WHERE refunded_at IS NULL;

-- 兼容:查询条件蕴含索引谓词,规划器选择部分索引
EXPLAIN (COSTS OFF)
SELECT refund_id, created_at
FROM refunds
WHERE refunded_at IS NULL
  AND created_at >= '2026-11-01'
ORDER BY created_at DESC;

-- 兼容:等值测试 NULL 也是对"是 NULL"这一事实的判断
EXPLAIN (COSTS OFF)
SELECT count(*)
FROM refunds
WHERE refunded_at IS NULL;

-- 不兼容:查询要看已退款行,谓词不蕴含,索引整个不适用
EXPLAIN (COSTS OFF)
SELECT refund_id, refunded_at
FROM refunds
WHERE refunded_at >= '2026-11-01';

How it works

The file runs SELECT / CREATE / EXPLAIN statements, touching refunds.

Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT aggregation; an ORDER BY that fixes the output order.

Putting it to use

Run the statement against the refunds table.

Core lines

EXPLAIN (COSTS OFF)
SELECT refund_id, created_at
FROM refunds
WHERE refunded_at IS NULL
  AND created_at >= '2026-11-01'
ORDER BY created_at DESC;
EXPLAIN (COSTS OFF)
SELECT refund_id, refunded_at
FROM refunds
WHERE refunded_at >= '2026-11-01';
CREATE INDEX idx_refunds_open
    ON refunds (created_at)
    WHERE refunded_at IS NULL;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
The references are `refunds`.