Index Cond Versus Filter
Index Cond pushes equality and range predicates into the index scan; non-indexed columns surface as a post-scan Filter with rows-removed cost.
Code
CREATE TABLE events (
id bigint PRIMARY KEY,
tenant_id integer NOT NULL,
kind text NOT NULL,
created_at timestamptz NOT NULL
);
CREATE INDEX idx_events_tenant_created ON events (tenant_id, created_at);
-- 索引覆盖 (tenant_id, created_at):等值 + 范围直接下推为 Index Cond
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id FROM events
WHERE tenant_id = 7 AND created_at > now() - interval '7 days';
-- kind 不在索引里:行仍由索引取回,但 kind = 'click'
-- 只能作为 Filter 在取出行之后逐行判断,EXPLAIN ANALYZE 的
-- Rows Removed by Filter 暴露这部分被浪费的扫描成本
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id FROM events
WHERE tenant_id = 7 AND created_at > now() - interval '7 days'
AND kind = 'click';
-- 设计依据:Index Cond 永远先于 Filter 生效,
-- 把高选择性的条件放进复合索引列,低选择性的留给 FilterWhat the code does
Several statements share this file — SELECT / CREATE / EXPLAIN, with events among the objects involved.
Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Run the statement against the events table.
Statements that matter
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id FROM events
WHERE tenant_id = 7 AND created_at > now() - interval '7 days'
AND kind = 'click';
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id FROM events
WHERE tenant_id = 7 AND created_at > now() - interval '7 days';
CREATE TABLE events (
id bigint PRIMARY KEY,
tenant_id integer NOT NULL,
kind text NOT NULL,
created_at timestamptz NOT NULL
);
Interactive Tools for This Topic
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.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.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
- Name the tables involved in this file.
- `events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.