Detect recent sequential scans in PostgreSQL
A high seq_tup_read means PostgreSQL is walking entire tables. This shows which ones and how badly.
The task
pg_stat_user_tables counts both seq_scan (sequential, full-table scans) and idx_scan (index scans) per table, plus seq_tup_read, the number of rows actually streamed during those full scans. A table with a handful of seq_scans but billions of seq_tup_read is a giant table being read end to end by queries that probably wanted an index.
The snippet
Written for PostgreSQL.
SELECT schemaname, relname AS table_name,
seq_scan, seq_tup_read,
idx_scan, idx_tup_fetch,
pg_size_pretty(pg_relation_size(relid)) AS table_size,
ROUND(seq_tup_read::numeric / NULLIF(seq_scan, 0)) AS avg_rows_per_scan
FROM pg_stat_user_tables
WHERE seq_scan > 0
ORDER BY seq_tup_read DESC
LIMIT 25;
仕組み
seq_tup_read counts the live rows returned by sequential scans, so it measures the work, while seq_scan only counts how often it happened: one scan a minute of a 100-million-row table costs far more than a thousand scans a minute of a 10-row lookup table. avg_rows_per_scan close to the table's row count means each scan reads the whole table; a much lower figure usually means scans that stop early, such as a LIMIT without a matching index. Check pg_stat_statements before adding an index, because some full scans are correct: a query that aggregates most of the table is faster as a sequential scan.
Variations
Only show big tables with many full scans
SELECT relname AS table_name, seq_scan, seq_tup_read, n_live_tup,
pg_size_pretty(pg_relation_size(relid)) AS table_size
FROM pg_stat_user_tables
WHERE n_live_tup > 100000 AND seq_scan > 100
ORDER BY seq_tup_read DESC;
Questions that come up
Can I reset seq_scan counters to measure a specific period?
pg_stat_reset() zeroes every table and index counter in the current database, which also restarts the clock for unused-index checks and anyone else's monitoring. pg_stat_reset_single_table_counters('orders'::regclass) limits the damage to one table. Copying the values into a table now and diffing later avoids resetting anything.
Every table shows some seq_scan. Is that bad?
No. Small tables are cheaper to scan than to probe through an index, and queries that read most of a table should scan it. Look at the top of the seq_tup_read ranking together with table size, and use pg_stat_statements to find the queries behind it. PostgreSQL 16 and later also record last_seq_scan per table, which tells you whether the scans are still happening.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.