Find the last ANALYZE time per table in PostgreSQL
Every table, ordered by how long ago its planner statistics were collected, with never-analyzed tables at the top.
The task
A quick staleness sweep answers one question per table: when were its planner statistics last collected, by anyone? Tables at the top have gone longest without fresh statistics, or have never had any. Those are worth checking first when a plan is bad in production but fine on a freshly loaded copy, where ANALYZE has just run.
The snippet
Written for PostgreSQL.
SELECT relname AS table_name,
n_live_tup,
last_analyze, last_autoanalyze,
GREATEST(last_analyze, last_autoanalyze) AS last_stats,
now() - GREATEST(last_analyze, last_autoanalyze) AS stats_age
FROM pg_stat_user_tables
ORDER BY COALESCE(GREATEST(last_analyze, last_autoanalyze), '1900-01-01'::timestamptz);
仕組み
last_analyze and last_autoanalyze are independent timestamps (manual ANALYZE versus autovacuum's analyze phase), so GREATEST picks whichever happened last; COALESCE with a sentinel puts never-analyzed tables first without a separate NULL branch. stats_age makes the ordering readable at a glance. Fresh on this list does not mean healthy on its own; pair it with n_mod_since_analyze from the statistics-staleness recipe to catch a table analyzed yesterday but rewritten a million rows since.
Variations
Generate ANALYZE statements for the stalest tables
SELECT format('ANALYZE %I.%I;', schemaname, relname) AS analyze_statement,
GREATEST(last_analyze, last_autoanalyze) AS last_stats
FROM pg_stat_user_tables
WHERE GREATEST(last_analyze, last_autoanalyze) < now() - interval '7 days'
OR (last_analyze IS NULL AND last_autoanalyze IS NULL)
ORDER BY n_live_tup DESC;
Questions that come up
ANALYZE vs VACUUM: which one do I need for slow plans?
ANALYZE refreshes planner statistics, so it is the one for bad plan choices. VACUUM reclaims dead tuples, so it is the one for bloat. Autovacuum does both, but on different schedules and thresholds, so a table can be well-vacuumed yet poorly analyzed or the reverse.
Does ANALYZE block queries?
No. ANALYZE takes a SHARE UPDATE EXCLUSIVE lock, which lets reads and writes continue; it conflicts only with VACUUM, another ANALYZE, CREATE INDEX CONCURRENTLY and most ALTER TABLE forms on the same table. It reads a random sample of about 30,000 rows rather than the whole table, so it is normally fine during business hours even on large tables. New plans pick up the statistics as soon as it commits.
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.