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.

SqlData Fetching

Code

snippet
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 生效,
-- 把高选择性的条件放进复合索引列,低选择性的留给 Filter

What 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

FAQ

Name the tables involved in this file.
`events` — referenced directly, no join needed.