List Partitions And Row Estimates With pg_inherits

pg_inherits lists every partition of a table; joined with pg_class it exposes partition bounds and the reltuples row estimates ANALYZE refreshes.

SqlResilience

Code

snippet
CREATE TABLE events (
    id          bigint GENERATED ALWAYS AS IDENTITY,
    occurred_at date NOT NULL,
    kind        text NOT NULL
) PARTITION BY RANGE (occurred_at);

CREATE TABLE events_2026q1 PARTITION OF events
    FOR VALUES FROM ('2026-01-01') TO ('2026-04-01');
CREATE TABLE events_2026q2 PARTITION OF events
    FOR VALUES FROM ('2026-04-01') TO ('2026-07-01');

INSERT INTO events (occurred_at, kind) VALUES
    ('2026-01-15', 'login'),
    ('2026-02-20', 'login'),
    ('2026-05-04', 'purchase');

ANALYZE events;

-- pg_inherits lists all partitions;reltuples 是 ANALYZE 刷新后的 row estimates
SELECT
    child.relname                              AS partition_name,
    pg_get_expr(child.relpartbound, child.oid) AS range_bounds,
    child.reltuples::bigint                    AS estimated_rows
FROM pg_inherits i
JOIN pg_class parent ON parent.oid = i.inhparent
JOIN pg_class child  ON child.oid  = i.inhrelid
WHERE parent.relname = 'events'
ORDER BY child.relname;

How the snippet works

The file runs SELECT / INSERT / CREATE statements, touching events, pg_inherits and pg_class.

Breaking the statements into their working parts: 2 JOINs combining rows across tables; a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

What to watch for

  • Row counts compound across 2 joins; make sure the join keys are indexed before adapting this to production data volumes.

Using it

The events table is the working surface here.

Key statements

CREATE TABLE events (
    id          bigint GENERATED ALWAYS AS IDENTITY,
    occurred_at date NOT NULL,
    kind        text NOT NULL
) PARTITION BY RANGE (occurred_at);
CREATE TABLE events_2026q1 PARTITION OF events
    FOR VALUES FROM ('2026-01-01') TO ('2026-04-01');
CREATE TABLE events_2026q2 PARTITION OF events
    FOR VALUES FROM ('2026-04-01') TO ('2026-07-01');

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`events`, `pg_inherits`, `pg_class`, combined through 2 joins.