Lesson 3.1

How the query planner works

The planner enumerates ways to execute a query and picks the cheapest by its cost model.

10mIntermediate11.1k students

Overview

Estimates in, plan out

The planner enumerates ways to execute a query and picks the cheapest by its cost model. That model runs on statistics about your data — how many rows, how distinct the values are, how they are distributed.

When statistics are stale, the estimates are wrong and the plan is wrong with them. A query that was fast yesterday and is slow today, with no code change, is very often this.

The gap between estimated and actual rows is your main diagnostic. An estimate of ten rows against an actual of a million explains almost any bad plan choice that follows.

In this lesson you will:

  • Understand cost-based plan selection
  • See why statistics matter
  • Recognise when an estimate is badly wrong

Resources

Previous Lesson
Next Lesson
How the query planner works — PostgreSQL for Application Developers — Vertex