Rows Removed By Filter Diagnoses Waste

On an unindexed column the planner seq-scans everything; Rows Removed by Filter in EXPLAIN ANALYZE shows how many rows the predicate discarded.

SqlData Integrity

Code

snippet
CREATE TABLE audit_events (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    kind        text NOT NULL,
    detail      text NOT NULL,
    occurred_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO audit_events (kind, detail)
SELECT
    CASE WHEN g % 1000 = 0 THEN 'security_alert' ELSE 'heartbeat' END,
    'event ' || g
FROM generate_series(1, 50000) AS g;
ANALYZE audit_events;

-- detail has no index, so the only plan is a seq scan; EXPLAIN ANALYZE then
-- reports how many rows the filter threw away after reading them all
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*) FROM audit_events WHERE detail = 'event 777';

CREATE INDEX audit_events_detail_idx ON audit_events (detail);
ANALYZE audit_events;

-- same query, one matching row: the plan switches to the index and the
-- filter waste disappears
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*) FROM audit_events WHERE detail = 'event 777';

Inside this example — Rows Removed By Filter Diagnoses Waste

SELECT / INSERT / CREATE / EXPLAIN statements share the script, touching audit_events and generate_series.

The pieces that do the work: a WHERE clause constraining which rows the statement operates on; COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Putting it to use

Point it at the audit_events table.

Core lines

INSERT INTO audit_events (kind, detail)
SELECT
    CASE WHEN g % 1000 = 0 THEN 'security_alert' ELSE 'heartbeat' END,
    'event ' || g
FROM generate_series(1, 50000) AS g;
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*) FROM audit_events WHERE detail = 'event 777';
CREATE TABLE audit_events (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    kind        text NOT NULL,
    detail      text NOT NULL,
    occurred_at timestamptz NOT NULL DEFAULT now()
);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`audit_events`, `generate_series`.