Indexing and query plans
One row among ten million
Section titled “One row among ten million”A table of orders has ten million rows, and a page of the website asks for the orders of one customer. With no help, the database has no choice but to read every page of the table and keep the rows that match. That is a sequential scan, and its cost grows with the size of the table.
An index is the help. PostgreSQL’s documentation compares it to the alphabetic index at the end of a non-fiction book: the reader scans the index quickly and flips to the right pages, instead of reading the whole book. In the database it is a second structure, sorted by one or more columns, whose entries point back at the rows. Once an index exists, the documentation says, no further intervention is required: the system updates it when the table changes, and uses it in queries when it thinks doing so would be more efficient than a sequential scan.
Mental model. An index is a sorted copy of some columns that points back at the rows. It buys read time with space and with work on every write, and the planner decides, query by query, whether the purchase is worth it.
How few pages a B-tree needs
Section titled “How few pages a B-tree needs”By default PostgreSQL’s CREATE INDEX creates a B-tree, which can handle equality and range queries on data that can be sorted. The last lesson described its structure: internal pages point to the next level down, and leaf pages point to table rows.
Count the reads with assumptions that keep the arithmetic easy. Rows fit about 100 to a page, so a table of 10 million rows is 100,000 pages. An index page holds 100 entries. A page is 8 kB in PostgreSQL, so 100 entries leave about 80 bytes for each: enough for a small key and a pointer, and not for a long text key, which fits fewer. With 100 entries per page, one level reaches 100 rows, two levels reach 100 × 100 = 10,000, three reach 1,000,000, and four reach 100,000,000. The number of levels is the smallest h for which 100^h is at least the number of rows.
| Rows | Table pages | A sequential scan reads | Index levels | A lookup reads (levels, plus one table page) |
|---|---|---|---|---|
| 1,000,000 | 10,000 | 10,000 pages | 3 | 4 pages |
| 10,000,000 | 100,000 | 100,000 pages | 4 | 5 pages |
| 100,000,000 | 1,000,000 | 1,000,000 pages | 4 | 5 pages |
| 1,000,000,000 | 10,000,000 | 10,000,000 pages | 5 | 6 pages |
For the ten million rows, a scan reads 100,000 pages and a lookup reads 5, which is 20,000 times fewer. Ten times more rows made the scan ten times longer and the lookup not one page longer. The tenfold step from 100 million to a billion rows adds a single level. That is why an index turns “grows with the table” into “grows with the logarithm of the table”.
What an index costs
Section titled “What an index costs”PostgreSQL’s documentation says it plainly: after an index is created, the system has to keep it synchronised with the table, which adds overhead to data manipulation operations. A table with five indexes does six pieces of work for each row it inserts: the row, and an entry in each of the five indexes. A unique constraint creates a unique B-tree index automatically, so even a rule you declared for correctness has this cost. An index on an expression, such as lower(email), is described as relatively expensive to maintain, because the derived expression has to be computed for each row insertion, and for some updates.
An index is also a bet on the queries. One that no query uses is pure cost: space, and a write to each insert. The right number of indexes is the smallest set that serves the access patterns of the previous lesson.
When the planner does not use the index
Section titled “When the planner does not use the index”The database does not run your query as written. A planner considers several ways to run it, estimates the cost of each, and picks the cheapest. A query plan is the plan it picked, a tree of nodes such as a sequential scan, an index scan or a join.
An index can lose. Suppose the query wants 5% of the 10 million rows, 500,000 of them. Through the index the rows are scattered over the table, and each can sit on a different page, so the database could be reading 500,000 pages in random order, when the whole table is 100,000 pages that it can read in sequence. PostgreSQL’s planner expresses this with two costs: a page fetched as part of a sequential series costs seq_page_cost, 1.0 by default, and a page fetched out of order costs random_page_cost, 4.0 by default. A crude comparison, if every row sits on its own page, is k × 4 against 100,000 × 1, and they are equal at k = 25,000 rows, which is 0.25% of the table. Beyond that share of the rows, reading everything is cheaper on paper.
That break-even is crude. It ignores the index pages, the cache and CPU time, and PostgreSQL also has bitmap scans, which fetch the pages in order. The documentation itself notes that random access to storage is normally much more expensive than four times sequential access, and that 4.0 is used because most random accesses, such as indexed reads, are assumed to be in cache. What the arithmetic does show is the principle: an index helps when it selects a small share of the table, and not when it selects most of it.
Reading a plan
Section titled “Reading a plan”EXPLAIN prints the plan: one line for each node, with the node type, the estimated start-up cost, the estimated total cost, the estimated number of rows and the estimated width of a row. These two plans are the PostgreSQL documentation’s own examples, on a table of 10,000 rows. The figures are the documentation’s, not this course’s.
Index Scan using tenk1_unique1 on tenk1 (cost=0.29..8.30 rows=1 width=244) Index Cond: (unique1 = 42) Seq Scan on tenk1 (cost=0.00..470.00 rows=7000 width=244) (actual time=0.030..1.995 rows=7000.00 loops=1) Filter: (ten < 7) Rows Removed by Filter: 3000The first plan finds one row through an index, with an estimated total cost of 8.30. The second scans the table and keeps 7,000 of the 10,000 rows, which is 70%. It is the shape the arithmetic above predicts: for a filter that keeps most of the table, the planner reads the table.
With the option ANALYZE, EXPLAIN actually runs the query and adds the true row counts and run time of each node, which is the second plan: it estimated 7,000 rows and found 7,000. When the two disagree, the planner chose its plan on a wrong guess. The estimates come from statistics collected by ANALYZE, which are random samples rather than exact counts, so a plan is only as good as the statistics behind it.
Which index helps which query?
Section titled “Which index helps which query?”An index helps the queries that its structure can answer. Equality and range conditions on the indexed column are what a B-tree handles. An index on a column stores its values as written, so it cannot answer a condition on a function of the column: the documentation’s example is lower(col1), which can use an index that is defined on the result of that function. A pattern such as LIKE 'foo%', anchored at the start of the string, can use a B-tree (outside the C locale the index needs a special operator class), while LIKE '%bar' cannot. A B-tree can also deliver rows already sorted, so an ORDER BY combined with LIMIT n can take the first n rows directly, without scanning the rest.
For several columns, the order matters. A multicolumn B-tree index is most efficient when the query constrains the leading, leftmost columns: equality on the leading columns, plus an inequality on the first column without an equality, limit the part of the index that is scanned. The documentation also advises using multicolumn indexes sparingly.
Nine queries, and one question for each: will an index like the one described help? The reasons are given for every answer.
Challenge
Will the index help?
Each statement describes a query and a B-tree index on a PostgreSQL table of 10 million rows. Decide whether the index helps that query or not. Every answer is explained.
Sorting needs JavaScript.
Categories
- The index helps
- The planner can use it to read far fewer pages than a scan.
- The index does not help
- The query reads most of the table, or the index cannot answer the question.
Check your answers at least once before looking at the answers.
What happens if the table grows tenfold?
Section titled “What happens if the table grows tenfold?”A service shows the last orders of a customer, 50 times a second. The table has 10 million rows. With an index on the customer, each request reads 5 pages, and the service reads 50 × 5 = 250 pages per second. Without it, each request scans 100,000 pages, so the service needs 50 × 100,000 = 5,000,000 pages per second.
Then the business grows tenfold, to 100 million rows. With the index each request still reads 5 pages. Without it each reads 1,000,000, so the scan needs 50,000,000 pages per second, ten times the load for the same traffic. Long before that, queries are queuing for the database, and the next lesson follows the queue into the connection pool: a query that takes ten times longer holds its connection for ten times longer.
Not every slow request is a missing index. A page that lists 50 orders and then asks for each order’s customer with a separate query sends 1 + 50 = 51 queries. If each query costs 2 ms, mostly the round trip, that is 102 ms of waiting, where a single query that joins the two tables sends one. The remedies are different and the cause is the same: the work grows with something that should not matter. Read the plan, and count the queries.
- Without an index a query reads the whole table. A B-tree reads one page per level and then the row: 5 pages for 10 million rows, 6 for a billion, against 100,000 and 10 million for a scan.
- Every index must be kept in step with the table, so every write pays for each one, and an unused index is cost with no benefit.
- The planner estimates the cost of each plan and picks the cheapest. An index loses when a query keeps most of the table: with PostgreSQL’s default page costs, a crude break-even is 0.25% of the rows.
EXPLAINshows the plan with estimated costs and rows, andEXPLAIN ANALYZEruns the query to show the true rows and times. A gap between them points at bad statistics.- A B-tree helps equality, ranges, anchored patterns and sorted output with a limit. It does not help a function of the column, a leading wildcard or a condition that keeps most rows, and a multicolumn index needs its leading columns in the query.
Next: how many copies of a fact to keep, and when to break the rule that says keep one.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.