AI Hints
Home›PostgreSQL Tutorial›Partitioning, VACUUM and Statistics
PostgreSQL · Lesson 90 of 120

Statistics and ANALYZE

How the planner guesses.

⏱ 2 min read▶ Video at 1:21:01🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

The planner picks a plan by guessing how many rows each step returns. Those guesses come from statistics, collected by analyze. Old statistics mean bad guesses, and slow plans.

  • Guess row counts
  • From statistics
  • ANALYZE

What Postgres knows

Pg stats shows the statistics for each column. Here, the most common countries in customers, and how often each appears. Run it. Postgres knows that about a quarter of customers are in the USA.

query.sqlsql
ANALYZE customers;

SELECT most_common_vals AS countries, most_common_freqs AS share
FROM pg_stats
WHERE tablename = 'customers' AND attname = 'country';
Output
ANALYZE
                 countries                 |                 share
-------------------------------------------+---------------------------------------
 {USA,UK,Australia,Canada,Ireland,Germany} | {0.252,0.234,0.172,0.154,0.104,0.084}
(1 row)

Keeping stats fresh

Autovacuum also runs analyze automatically. Run analyze yourself after a big load. Raise the statistics target for columns with very uneven data. And extended statistics help when columns are related.

keyvalue
Autoanalyzeautomatic
After loadsANALYZE
SET STATISTICSmore detail
CREATE STATISTICSrelated columns

Summary

Statistics drive the planner's guesses, and analyze keeps them fresh. Next, finding slow queries with pg stat statements.

Key takeaways
  • pg_stats
  • ANALYZE
  • Good guesses
Next up: pg_stat_statements — find the slow queries