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.
Code
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
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
- Which tables appear in this script?
- `audit_events`, `generate_series`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.