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.
Code
-- 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
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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does this file reference?
- The references are `refunds`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.