Sub topic 1
Reading Query Plans with EXPLAIN: What EXPLAIN Shows and Why It Matters
This chapter assumes you can write SELECT queries with WHERE and JOIN, that you know a database index speeds up lookups, and that you can run SQL in psql or another client. Examples use PostgreSQL.
Prerequisites
You should be comfortable with SELECT, WHERE, JOIN, GROUP BY and ORDER BY, and know what an index is. You should also be able to run queries in psql or another SQL client.
What EXPLAIN shows and why it matters
EXPLAIN is a command that asks the database planner how it would run a query. The planner is the part of the database that chooses an execution strategy. EXPLAIN prints that strategy as a plan and does not run the query.
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;A plan explains slow queries. It shows whether the database reads a whole table or uses an index, and it shows how many rows it expects at each step.
Reading a plan from the inside out
A plan is a tree. Each line that starts with an arrow or a node name is a node, and indented nodes feed rows upward to their parent. Read the deepest nodes first, because they produce rows that the nodes above them consume.
What the cost numbers mean
Each node shows cost=startup..total. Costs are unitless numbers that the planner uses to compare plans. They are not milliseconds. The first number is the estimated cost to return the first row, and the second is the estimated cost to return all rows. Use costs to compare alternatives for the same query, not to predict run time.
Estimated rows and width
rows is the number of rows the planner expects that node to output. width is the estimated average size of each row in bytes. The planner computes these from table statistics, so stale statistics lead to poor choices.
Index Scan using orders_customer_id_idx on orders (cost=0.43..8.45 rows=3 width=40)
Index Cond: (customer_id = 42)Sequential, index, index-only and bitmap scans
A scan is how a node reads a table.
- Seq Scan reads every row. It suits small tables or queries that return a large share of rows.
- Index Scan looks up matching rows through an index, then fetches each row from the table. It suits selective filters that return few rows.
- Index Only Scan answers the query from the index alone. It needs the table's visibility map to be current, which VACUUM maintains.
- Bitmap Heap Scan builds a bitmap of matching row locations from one or more indexes, then reads those pages in order. It suits medium selectivity.
> Never mind the arrows.
Exercise
A query on a 10-million-row table returns 8 million rows and the plan shows Seq Scan. Is that a problem?
Show answer
No. Reading most of the table is faster with a sequential scan, because index lookups for 8 million rows cost more than one pass over the table.