Skip to content
About
Main content
Query Engines

Query Planning & Optimization

How does a system choose a plan for a question when the facts that decide the best plan are unknown until the plan has run?

Who this mechanism is for: a developer who writes SQL, uses dashboards or ORMs, and has seen the words "execution plan" or EXPLAIN but has never studied how a database chooses a plan. You do not need to know how a join is implemented inside the engine. Every technical term is explained the first time it appears, and again in the glossary at the end.

The story we will follow

Ananya is a data engineer at Kiranamart, an online grocery company with about 400 stores and a web shop. Dev is the analytics lead. He owns the dashboards, which are built with a BI tool (a business-intelligence tool that writes SQL automatically from drag-and-drop choices). Dev asks the awkward questions: "Why is this slow today when it was fast yesterday?"

Kiranamart keeps its data in a Postgres-style SQL warehouse. The main table is orders, with about 1 billion rows, one partition per day, loaded every night and growing about 1% per load. Next to it sit order_items and the small dimension tables customers, products, stores, dates, promotions and couriers. The dashboards also sit on a stack of SQL views, for example v_sales_enriched. Later, the same data is also exported as files in object storage for a second query engine.

Each article below opens with a problem that looks like a bug: a report that was fast and is now slow, a query that gives the same answer as another but takes a thousand times longer. At the end of the article we go back to Ananya and Dev and solve it. The theme repeats in every article, and it is the main idea of this mechanism:

How this mechanism is organized

After that: a summary, hands-on labs, interview questions and a glossary.

What do I do, and what does each option cost?

Can I see it myself?

Can I reason about it under questioning?

Trade-offs

The tensions this mechanism takes a position on. Each recurs across mechanisms.

Recurring principles

Ideas this mechanism meets that keep coming back, mechanism after mechanism.

Show all 12 principles