Video in progress

Why does the planner misestimate the row count when two columns are correlated, and how do you fix it?

By default the planner treats columns as independent and multiplies their selectivities. For correlated conditions like city='Toshkent' AND region='Toshkent' this cuts the estimate many times over; you can teach it the correlation with CREATE STATISTICS.

📖 Answer

Example: city and region in an address table. Every row in the city of Tashkent is also in the Tashkent region (or vice versa), so they are nearly the same information. The planner computes it like this:

sel(city='Toshkent') = 0.1
sel(region='Toshkent') = 0.1
estimate = 0.1 * 0.1 = 0.01   -- actually 0.1

A 10x underestimate leads to a nested loop and the wrong join order.

CREATE STATISTICS st_address_city_region (dependencies, ndistinct, mcv)
    ON city, region FROM address;
ANALYZE address;
  • dependencies: how much one column determines the other;
  • ndistinct: the correct number of groups for GROUP BY city, region;
  • mcv (PG12+): a list of the most common pairs, the most precise option.

There are other causes too. Stale statistics (autoanalyze hasn't run yet after a big import): run ANALYZE by hand. Values very unevenly distributed: enlarge the sample for the column with ALTER TABLE ... ALTER COLUMN ... SET STATISTICS 1000. If an index is built on an expression (lower(email)), statistics are also collected for the expression, which many people don't know.