Tag: Postgresql

1 entry found

How PostgreSQL Estimates Your Queries (And Why It Sometimes Gets It Wrong)

How PostgreSQL Estimates Your Queries (And Why It Sometimes Gets It Wrong)

11 min read

Every query starts with a plan. Every slow query probably starts with a bad one. And more often than not, the statistics are to blame. But how does it really work?

PostgreSQL doesn’t run the query to find out — it estimates the cost. It reads pre-computed data from pg_class and pg_statistic and does the maths to figure out the cheapest path to your data.

In the ideal scenario, the numbers read are accurate, and you get the plan you expect. But when they’re stale, the situation gets out of control. The planner estimates 500 rows, plans a nested loop, and hits 25,000. What seemed like an optimal plan turns into a cascading failure.