Sub topic 3
What pg_class knows: reltuples and relpages
Before the planner looks at any column statistics, it needs two basic facts about a table: how many rows it holds and how many disk pages it occupies. PostgreSQL keeps both in the system catalog pg_class. This chapter shows where those numbers come from, how the planner turns them into a row estimate for a scan, and how they go wrong.
This chapter assumes you can run psql, read simple EXPLAIN output, and know that ANALYZE collects statistics. The examples use the orders table from the previous chapter, with 100,000 rows loaded and ANALYZE orders already run.
The three columns that matter
pg_class has one row for every table, index, view, sequence, and similar object. Three of its columns describe size.
| Column | Type | Meaning |
|---|---|---|
| `relpages` | integer | Number of disk pages the relation occupied at the last update. One page is 8 kB by default. |
| `reltuples` | real | Estimated number of live rows at the last update. |
| `relallvisible` | integer | Number of pages the visibility map marks all-visible. Index-only scan costing uses it. |
Look at them for orders:
SELECT relname, relkind, reltuples::bigint AS reltuples, relpages, relallvisible
FROM pg_class
WHERE oid = 'orders'::regclass;Filtering on oid = 'orders'::regclass is safer than relname = 'orders'. A name match can return a same-named table from another schema, and the cast follows your search_path. Expect reltuples near 100000. With the row layout from the previous chapter, relpages should land at roughly 700 to 750, though the exact value depends on your version and platform.
Indexes have rows in pg_class too, with the same columns:
SELECT relname, relkind, reltuples::bigint AS reltuples, relpages
FROM pg_class
WHERE oid IN ('orders'::regclass, 'orders_pkey'::regclass);Here relkind is r for an ordinary table and i for an index. For an index, relpages is its size in pages, which feeds index scan cost. reltuples is the number of entries the index holds.
Because reltuples is a real, it is a floating-point value. Cast it to bigint when you want to read it, or you may see output in scientific notation for large tables.
Who writes these numbers
reltuples and relpages are not maintained on every insert, update, or delete. Only certain commands write them:
ANALYZE, including the analyze step ofVACUUM ANALYZEand autoanalyze.VACUUM, including autovacuum.CREATE INDEXandREINDEX, for the index and its table.- A few rewriting commands such as
VACUUM FULLandCLUSTER.
Between those events the values go stale. A table that grows by a factor of ten after the last ANALYZE still shows the old reltuples. This staleness is why the planner does not trust these columns blindly, as the next section shows.
ANALYZE does not count every row. It reads a random sample of pages and extrapolates, so reltuples is an estimate even right after ANALYZE. VACUUM may skip pages that the visibility map shows as unchanged, and it extrapolates for those pages too. Both count only live rows, so dead tuples do not inflate reltuples.
A table that has never been vacuumed or analyzed shows reltuples = -1 in PostgreSQL 14 and later. The -1 means "unknown". Before version 14 the same state showed 0, which was indistinguishable from a truly empty table.
CREATE TABLE scratch (x int);
SELECT reltuples, relpages FROM pg_class WHERE oid = 'scratch'::regclass;On PostgreSQL 14 or later this returns -1 and 0.
How the planner uses them
You might expect the planner to read reltuples and use it as the row estimate for a sequential scan. It does not. The planner asks the storage layer for the current number of pages in the table file, which is cheap because it only checks the file size. It then scales the stored row density to that page count.
The diagram below shows the steps.
In short, estimated rows = (reltuples / relpages) * current_pages. If the table has not changed in size, the result equals reltuples. If the file has grown, the estimate grows with it, even though no one updated pg_class. This scaling is a partial defense against stale statistics. It assumes new pages hold the same number of rows as old ones.
Two special cases follow from the same logic:
- If
relpagesis 0 orreltuplesis -1, the planner has no density. It estimates one from the column widths in the table definition. It also assumes the table has at least 10 pages, so a freshly created table is not treated as empty. - If the table has been vacuumed but never analyzed,
reltuplesis known but column statistics inpg_statsare not. Row counts are decent, and selectivity estimates fall back to defaults.
Watching the scaling happen
Compare the stored page count with the real one, then see what the planner estimates:
SELECT relpages,
pg_relation_size('orders') / current_setting('block_size')::int AS actual_pages
FROM pg_class
WHERE oid = 'orders'::regclass;
EXPLAIN SELECT * FROM orders;Both page counts should match, and the plan should show rows=100000. Now double the table and look again straight away:
INSERT INTO orders (customer_id, status)
SELECT (random() * 1000)::int, 'shipped'
FROM generate_series(1, 100000);
SELECT relpages,
pg_relation_size('orders') / current_setting('block_size')::int AS actual_pages
FROM pg_class
WHERE oid = 'orders'::regclass;
EXPLAIN SELECT * FROM orders;relpages is unchanged, but actual_pages is about twice as large. The EXPLAIN line should show rows close to 200000 even though reltuples still says 100000. The planner multiplied the old density by the new page count.
Where the scaling fails
The density trick only works when new data looks like old data. It breaks in a few common cases.
Deletes without vacuum. If you delete half the rows, the file does not shrink. The page count is unchanged, so the planner's estimate stays near the old reltuples until a vacuum or analyze runs. A scan will still read every page, so the cost is accurate, but the row estimate feeds into join planning and is too high.
Bloat. After heavy updates, a table can hold many dead tuples. If an analyze runs at that point, reltuples counts only live rows while relpages includes the dead space. The density is then low, which is correct for the current file. If the table is later compacted, the estimate shifts.
Uneven growth. If the new rows are much wider or narrower than the old ones, rows per page changes, and the stored density is wrong for the new pages.
Never-analyzed tables. Right after a bulk load into a new table, the planner works from width-based guesses. A plan that looks fine on a ten-row test table can look very different at scale. Run ANALYZE after bulk loads.
How reltuples feeds cost
For a sequential scan, PostgreSQL computes cost from the page count and the row count. With default settings, seq_page_cost is 1.0, cpu_tuple_cost is 0.01, and cpu_operator_cost is 0.0025:
cost = pages * seq_page_cost + rows * cpu_tuple_cost
+ rows * cpu_operator_cost * (number of filter operators)For orders with about 735 pages and 100,000 rows, the unfiltered scan cost is about 735 + 1000 = 1735. With a one-operator WHERE clause, add 100000 * 0.0025 = 250, giving about 1985. You can confirm this by comparing EXPLAIN SELECT * FROM orders with the same query plus WHERE status = 'pending' and reading the cost range. Treat the page count as approximate, since your table may differ slightly.
The fact that cost depends directly on both numbers is why wrong values here can flip a plan from a sequential scan to an index scan, or the reverse.
Checking and refreshing
To see how stale the stored values are for every user table, compare them with the live file size:
SELECT c.relname,
c.reltuples::bigint AS stored_rows,
c.relpages AS stored_pages,
pg_relation_size(c.oid) / current_setting('block_size')::int AS actual_pages
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname = 'public'
ORDER BY actual_pages DESC;A table where actual_pages is far from stored_pages has changed a lot since its last update. To refresh it, run:
ANALYZE orders;VACUUM alone also updates reltuples and relpages, but it does not collect the column statistics in pg_stats. VACUUM ANALYZE does both in one command.
Summary
pg_classstoresreltuples(estimated live rows),relpages(pages), andrelallvisible(all-visible pages) for each table and index.- Only
ANALYZE,VACUUM, index builds, and a few rewrite commands update these values. - The planner computes estimated rows as stored density times the current number of pages, so growth is partly tracked without any update.
reltuples = -1means "never vacuumed or analyzed" on PostgreSQL 14 and later.- Deletes, bloat, and uneven row widths make the scaled estimate drift.
Exercise
A table has reltuples = 50000 and relpages = 500 in pg_class. Without any vacuum or analyze, a batch job inserts rows until the table file is 1500 pages, and the new rows are the same size as the old ones. What row estimate does the planner use for a sequential scan, and why?
Show answer
About 150000 rows. The planner computes density as 50000 / 500 = 100 rows per page, reads the current file size of 1500 pages, and multiplies: 100 * 1500 = 150000. It does not need pg_class to be updated, because it scales the stored density to the current page count.
Exercise
You delete 60% of the rows in a large table and run nothing else. EXPLAIN on a plain SELECT * from the table still shows the old, high row count. Explain why, and name two commands that would fix the stored values.
Show answer
Deleting rows does not shrink the table file, so the current page count is unchanged, and pg_class still holds the old reltuples and relpages. The density times page count calculation therefore returns the old row count. Running ANALYZE or VACUUM (or VACUUM ANALYZE) recounts live rows and updates reltuples and relpages. Autovacuum will eventually do this as well.
Exercise
What does reltuples = -1 mean on PostgreSQL 14 or later, and how does it differ from reltuples = 0?
Show answer
-1 means the table has never been vacuumed or analyzed, so the row count is unknown and the planner falls back to a width-based estimate. 0 means the table was counted and found to have no live rows.