Fast Count Estimates From pg_class

count(*) must scan every row while pg_class.reltuples hands back the planner row estimate instantly; ANALYZE keeps the estimate fresh.

SqlData Fetching

Code

snippet
-- fast count estimates: count(*) scans, pg_class.reltuples reads statistics
CREATE TABLE events (
    event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    kind     text NOT NULL
);
INSERT INTO events SELECT g, 'click' FROM generate_series(1, 100000) g;
ANALYZE events;

-- exact count: scans the whole table and slows down as rows grow
SELECT count(*) FROM events;

-- estimated count: reads planner statistics directly and returns instantly
SELECT reltuples::bigint AS estimated_rows
FROM pg_class
WHERE relname = 'events';

-- estimate drift comes from ANALYZE sampling plus writes after the last analysis; use count(*) only when you need the exact number
SELECT
    (SELECT reltuples::bigint FROM pg_class WHERE relname = 'events') AS estimated,
    (SELECT count(*) FROM events) AS exact;

How the snippet works

What runs here is SELECT / INSERT / CREATE — events, generate_series and pg_class are the objects involved.

In terms of clauses, the statements use: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Point it at the events table.

Statements that matter

SELECT
    (SELECT reltuples::bigint FROM pg_class WHERE relname = 'events') AS estimated,
    (SELECT count(*) FROM events) AS exact;
SELECT reltuples::bigint AS estimated_rows
FROM pg_class
WHERE relname = 'events';
INSERT INTO events SELECT g, 'click' FROM generate_series(1, 100000) g;

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`events`, `generate_series`, `pg_class` — referenced directly, no join needed.