How the Query Optimizer Builds an Execution Plan

Parse, rewrite, then choose access paths and join order by cost using statistics. Why bad statistics produce bad plans, and how to see the plan.

In this chapter

How a database builds a query plan

More on Query execution and the optimizer

Keep learning

Overview

Estimated rows far from actual Stale or coarse statistics Plan flips after a bulk load or purge Data crossed a cost switch point Full scan although an index exists Wrong join order Bad estimate for the first table One query always picks the wrong index Estimate and reality disagree for this filter chapters · query execution and the optimizer How a database builds a query plan SQL says what you want, not how. The planner tidies the query, prices every way to run it, and keeps the cheapest. The prices come from statistics, so stale statistics give bad plans.

1. From text to rows in five stages

Only stage 4 looks at data sizes. Stage 3 applies rules that are always safe. Pick a rule to see what the planner really works on. The join methods the plan can pick are in join methods.

2. Cost: the same query, a different best plan

A scan pays a fixed price: every page, every row. An index plan pays per match, because each hit is a jump to the row. Drag the slider past the dashed line, then ask for indexed columns only. This crossing is why an index can seem ignored. With several tables the planner also searches join orders, and their number explodes. Possible join orders for n tables (n!) What planners do search all of them (dynamic programming) greedy or heuristic search with pruning An order costs roughly rows of the first table × cost of one probe into the next, and so on. A bad first estimate is multiplied through the plan.

3. Statistics, histograms and plan flips

Sampling: of 2,000 index pages the engine reads 20, counts 4,000 distinct values in them, and scales up by 100 to estimate about 400,000 distinct values for the whole index. sampled: 20 of 2,000 pages distinct in sample: 4,000 × 100 → ≈ 400,000 distinct Stored: row count, pages, distinct values per column, optional histograms. Refreshed after a share of the table changes, or by hand. Between refreshes they age. Some engines also count rows in the index at plan time for simple ranges, which softens stale stats. A bulk load or purge can move data across a switch point while the statistics still describe the old table. Drag the real share and watch the plan stay put until you refresh. A distinct count assumes every value is equally common. A histogram stores how often values occur, which matters for skewed columns. It is a snapshot too. The stale-statistics interview case plays this out end to end.

4. Reading the plan as an operator tree

Every engine prints a tree like this: scans and lookups at the leaves, joins, sorts and aggregates above. Asking for actuals runs the statement, so wrap a write in a transaction you roll back.

5. Hints: a last resort

Justified when actuals prove the plan wrong, refreshing statistics and better indexes did not help, and the data shape is stable. Documented next to the query with a reason and a date to re-check. A liability when it hides stale statistics, names an index that may be dropped, or fights data growth. Fix the input first: statistics, a composite index, or a rewrite as in the slow query case and the index choice case.

Symptom, cause and lever

Plan problems and where to look Usual cause ✓ Recap ⚙ In real engines

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.