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.
Code
-- 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
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.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.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.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.
FAQ
- Which objects does the SQL touch?
- `events`, `generate_series`, `pg_class` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.