In PostgreSQL, which pg_stat_user_tables counters suggest a table is missing an index, and how do you avoid false alarms when reading them?
answer
- scans that read whole tables
- rows read per sequential scan
- compare with index scans
- a NULL idx_scan has a meaning
basics
~20 sLook for large tables where seq_scan is high, seq_tup_read divided by seq_scan is close to the row count, and idx_scan is low or NULL. Then confirm with the actual queries, because small tables, exports and batch jobs scan sequentially by design.
solid answer
~40 sIn `pg_stat_user_tables`, `seq_scan` counts sequential scans started on the table and `seq_tup_read` the live rows they returned, so `seq_tup_read / seq_scan` is the average rows per scan. If that average is near `n_live_tup` on a big table and `seq_scan` keeps climbing, queries are reading the whole table repeatedly. `idx_scan` is the sum of scans over the table's indexes and is NULL when the table has no index at all. I diff two snapshots taken an hour apart, because the counters are cumulative since the last reset. Then I find the statements with `pg_stat_statements` and check them with `EXPLAIN` before adding an index. Small lookup tables, `pg_dump`'s `COPY` and reporting jobs are expected sequential scans.
code
sql · 13 linesCREATE TABLE table_stats_snap AS
SELECT now() AS taken_at, relid, relname, seq_scan, seq_tup_read, idx_scan
FROM pg_stat_user_tables;
-- one hour later
SELECT t.relname,
t.seq_scan - s.seq_scan AS seq_scans_in_window,
t.seq_tup_read - s.seq_tup_read AS rows_read_in_window,
coalesce(t.idx_scan, 0) - coalesce(s.idx_scan, 0) AS idx_scans_in_window
FROM pg_stat_user_tables t
JOIN table_stats_snap s USING (relid)
ORDER BY rows_read_in_window DESC
LIMIT 10;go deeper
Know that pg_stat_user_tables counts sequential and index scans per table, and that many full scans of a big table point at a missing index.
Explain seq_tup_read divided by seq_scan, why idx_scan can be NULL, and why small tables and pg_dump produce harmless sequential scans.
Show the workflow: window the counters by diffing snapshots, tie the table to statements through pg_stat_statements, verify with EXPLAIN, then build the index concurrently and confirm the counters move.
Discuss when an index is the wrong fix: a reporting workload that should move to a replica or a summary table, and the write cost every new index adds.
## What the table counters measure PostgreSQL's cumulative statistics system keeps one row per table of the current database in `pg_stat_all_tables`; `pg_stat_user_tables` is the same view filtered to user tables. The columns that matter for index hunting: | Column | Meaning | |---|---| | `seq_scan` | sequential scans started on the table | | `seq_tup_read` | live rows returned by those sequential scans | | `last_seq_scan` | time of the most recent sequential scan | | `idx_scan` | index scans summed over all of the table's indexes; NULL if it has none | | `idx_tup_fetch` | live rows fetched through index scans | | `n_live_tup` | estimated live rows, a cheap stand-in for table size | All of them are counters since the last statistics reset, and each backend flushes its counts to shared memory before going idle, at most about once a second, so a running transaction is not yet reflected. They are collected only while `track_counts` is on, which is the default because autovacuum depends on it. ## A query that ranks suspects The signal is not a high `seq_scan` alone but many scans that each read most of a big table: ```sql SELECT relname, seq_scan, idx_scan, n_live_tup, seq_tup_read / NULLIF(seq_scan, 0) AS avg_rows_per_seq_scan, last_seq_scan, pg_size_pretty(pg_total_relation_size(relid)) AS total_size FROM pg_stat_user_tables WHERE n_live_tup > 100000 ORDER BY seq_tup_read DESC LIMIT 15; ``` ## Reading the numbers 1. **Rank by `seq_tup_read`**, the total rows read sequentially, because that is the work done. 2. **Check the average per scan.** An average close to `n_live_tup` means full-table scans; a small average on a big table usually means a `LIMIT` stopped the scan early. 3. **Look at `idx_scan`.** NULL means the table has no index, not even a primary key. Zero means indexes exist but no query used them. 4. **Check recency.** `last_seq_scan` tells you whether the pattern is still happening or ended weeks ago. 5. **Measure a window.** Copy the view into a table with `now()`, wait an hour, and subtract; lifetime totals mix last year's workload with today's. ## False positives and real positives Some sequential scans are the right plan, or come from tooling rather than the application: - **Small tables.** For a few hundred rows of `cms.site_setting`, reading every page usually beats an index, and the planner correctly chooses it. - **Dumps and exports.** `pg_dump` reads table data with `COPY`, and `COPY ... TO` starts a sequential scan, so every nightly dump adds one scan per table. - **Reports.** A job that aggregates every row of `cms.page_view` needs the whole table, and no index would help. The real positives in a CMS tend to look like these: - **Foreign keys without an index on the referencing side.** Deleting a row from `cms.page` makes PostgreSQL look for referencing rows in `cms.comment`; without an index on `comment.page_id`, each deleted page costs a sequential scan of the comment table. - **Filters on unindexed columns**, such as listing `cms.media_asset` by `uploaded_by` on every editor page load. ## Caveats about the counters themselves The numbers are only as good as the window they cover: - **Per server.** Each server keeps its own counters. A hot standby counts the read-only queries it serves, and none of that appears on the primary, so check every server that takes reads before deciding a table is never scanned. - **Reset events.** Counters start from zero after a statistics reset, a crash, an immediate shutdown, a start from a base backup or point-in-time recovery. Read `pg_stat_database.stats_reset` before comparing totals. - **Partitioned tables.** Scans are counted on the partitions that were actually read, so a missing index usually shows up on every partition rather than on the parent. - **Timestamps are approximate.** `last_seq_scan` and `last_idx_scan` are based on the most recent transaction stop time, which is good enough for "still happening" but not for correlating with a single log line. - **Current database only.** `pg_stat_user_tables` shows the database you are connected to; check each database of the cluster separately. ## From suspect to index The table counters say which table is scanned, not by which statement. Close the loop: - find the statements touching the table in `pg_stat_statements`, which the query-stats sibling covers; - run `EXPLAIN (ANALYZE, BUFFERS)` on them and confirm a `Seq Scan` with a selective filter, reading plans being the explain leaf's subject; - build the index with `CREATE INDEX CONCURRENTLY`, then watch `idx_scan` rise and `seq_tup_read` flatten. The opposite question, which existing indexes are never used, is answered by `pg_stat_user_indexes` and belongs to the index-upkeep leaf.
- Why does a table with no indexes show NULL rather than 0 in idx_scan?`idx_scan` is defined in the view as the sum of scan counts over the table's indexes, found through a LEFT JOIN to `pg_index`. With no index, there is nothing to sum and the aggregate is NULL. Zero means indexes exist and none has been scanned since the last reset.
- Deleting old pages from cms.page is slow and cms.comment shows thousands of new sequential scans. What is happening?The foreign key from `cms.comment.page_id` to `cms.page` makes PostgreSQL check for referencing rows on every delete. PostgreSQL does not create an index on the referencing column automatically, so each check is a sequential scan of `cms.comment`. An index on `comment.page_id` turns each check into an index lookup.
- Can these counters be trusted on a server that just failed over?Not as history. The counters are kept per server and reset after an unclean start, such as crash recovery or starting from a base backup. A promoted standby counts what it served. Check `pg_stat_database.stats_reset` and measure a fresh window before drawing conclusions.
- A high seq_scan count on its own proves the table needs an index.
- seq_tup_read counts dead rows too, so it mostly measures bloat.
- idx_scan of NULL means the indexes exist but were never used.
- PostgreSQL automatically indexes the referencing column of every foreign key.
- The counters cover only the last 24 hours, so no baseline is needed.