Courses / Databases for Backend Interviews / Chapter 18
Module 8 · Indexes and query plans · Chapter 18 of 27
Query Plans: EXPLAIN, Statistics and Join Algorithms
Builds on SQL Essentials: Tables, Changes, Queries, Joins, Subqueries and Views, Filtering Patterns: Existence, Exclusion, Aggregate Filters and Top-N per Group and Indexes: B-Trees, Composite Keys, Covering and Partial Indexes. Next up: Transactions: ACID, the Write-Ahead Log and Crash Recovery.
Part 1 · Reading EXPLAIN
From a query to a plan
A slow query is rarely fixed by guessing. EXPLAIN shows the plan the server chose, and a plan is something you can read.
SQL says what you want, not how to get it. The planner (also called the optimiser) turns a query into a plan, a tree of nodes such as scans, joins, sorts and aggregates. The executor runs the tree from the bottom: leaf nodes read tables, and each node passes rows up to its parent. The planner builds several candidate plans, estimates a cost for each, and picks the cheapest. Everything in an EXPLAIN is an estimate until you add ANALYZE.
Costs are in arbitrary units, tied to the planner's cost settings. By convention a sequential page read costs 1.0 (seq_page_cost), and every other cost is relative to that. Each node shows a startup cost, the work before it can return its first row, and a total cost. A parent's cost includes its children. rows is the number of rows the node is expected to emit, not the number it scans, and width is the average size of an output row in bytes.
This lesson uses two tables: customers with 50,000 rows, and orders with 5 lakh rows, one per minute from 1 January 2026. Both have a primary key, and nothing else is indexed yet. The query counts orders per city since 1 June 2026. The runs use PostgreSQL 18.6 and one process per query: parallel workers are switched off with SET max_parallel_workers_per_gather = 0, which keeps the plan short. The session time zone is Asia/Kolkata, which is why times in the plans carry +05:30.