The labs on this site need JavaScript to run. The same content is written out below.
Learn › Database › Indexes and execution plans
Indexes and full table scans
Why is the index not used even though it exists?
Why it exists — Without something arranged separately, even if only a few rows match the condition, the database must check every row one by one, so lookups get slower as the table grows. An index builds a B-tree from the values of a column and lets the search narrow down from the top, so that even with 10 million rows it finds the position of the wanted row after only a few levels.
Where it's used today — Create it on columns that often appear in WHERE, JOIN, and ORDER BY, such as finding a member by email, looking up an order by order number, and cutting an order list by period. MySQL and PostgreSQL create an index automatically for a primary key and a UNIQUE constraint. For a column with few distinct values, where any value you look up matches about half of the rows, the number of rows to read hardly decreases even through an index, so the benefit is small.
There are two ways to find the rows that match a condition: read the table from beginning to end (a full table scan), or find the positions in an index and read only those rows. Which one is cheaper depends on the share of rows the condition matches, and the optimizer chooses by looking at statistics.
Checked against real execution · All 54 combinations run on MySQL 8.4 and compared (plans, Handler_read counters, and optimizer cost estimates)
Concepts in this lab
- Index
- A data structure that keeps the values of specific columns separately, in sorted form, so that the wanted rows of a table can be found quickly. Without one, the whole table must be read to find the rows that match a condition. Reads get faster, but it must also be updated every time data is inserted, updated, or deleted, so it costs write performance and storage space.
- B-tree index
- Why it exists — A binary tree on disk has one key per node, so its height grows when there are many rows, and it is slow because every node read is a disk read. A B-tree puts many keys in one disk page, so it finds a value with a few page reads.
- Where it's used today — In MySQL InnoDB and PostgreSQL, a B-tree index is created when you do not specify the kind with CREATE INDEX. For lookups that only look for the same value, you can also choose a hash index in PostgreSQL.
- The index structure that most relational databases use by default. It is a balanced tree that keeps values sorted, and each node holds many keys, so the height of the tree is low. You can find a value by going down only a few levels from the root. Because the values are sorted, it is used not only for equality lookups but also for range lookups and sorting.
- Full table scan
- A way of finding the rows that match a condition by reading every row of the table from beginning to end. It is chosen when no index can be used for the condition, or when an index exists but the optimizer judges that reading everything is better because too many rows match the condition. When it is used to find a few rows in a large table, it causes performance problems.
- Query execution plan (EXPLAIN)
- The plan that the database decides on for how to run a query. It shows which indexes are used, in what order the tables are joined, and how many rows the database expects to read. You view it by putting EXPLAIN in front of the query, and it is the starting point for finding the cause when a query is slow.
- Optimizer
- Why it exists — If developers had to decide which index to read and in what order to join for every query, they would have to rewrite queries whenever the amount and distribution of data change. With an optimizer, the SQL states only the result that is wanted, and the database chooses how to read based on the statistics at that time.
- Where it's used today — You usually do not think about it, but when an EXPLAIN result differs from what you expect, in MySQL you collect fresh statistics with ANALYZE TABLE or correct the choice with a hint such as FORCE INDEX.
- The database component that chooses, among the several ways a SQL statement can be executed, the one that is expected to cost the least. It decides based on statistics such as the number of rows in a table and the distribution of values. If the statistics differ from the real data, it can choose an inefficient way.
- Cardinality and selectivity
- Cardinality is the number of distinct values in a column. The more distinct values there are (for example, a national ID number or an email address), the fewer rows one condition leaves and the more effective an index is. The fewer kinds of values there are (for example, gender), the more rows match a condition and the less effective an index is. Selectivity is the cardinality divided by the number of rows in the table; the closer it is to 1, the better a single condition narrows down the rows.
Try these
- Default settings — Of 100,000 rows, only 0.1% match the condition. The index reads only 100 rows.
- Same query, no index — To find 100 rows, it reads all 100,000 rows.
- When half the rows match — Even with an index, the optimizer chooses a full table scan.
- Forcing the index anyway — It reads only half the rows, but the cost the optimizer calculated is higher than for a full table scan.
- Near the boundary: 10% and 20% — Run it at 10%, then change to 20% and compare.
- No index on 10,000,000 rows — The rows read grow in proportion to the extra rows.
- More rows move the boundary — At 10% the index was chosen with 100,000 rows, but with 10,000,000 rows a full table scan is chosen.
Running with the default settings
- The query arrives. The orders table has 100,000 rows and amount is spread evenly from 0 to 99,999, so the condition amount < 100 matches 100 rows (0.1%). The optimizer does not know this in advance, so it decides how to run the query from estimates based on statistics.
- Method 1, full table scan: read the table from beginning to end, in order, and check the condition on each row. In the statistics the table has about 99,960 rows. Reading in order is cheap per row. The estimated cost MySQL calculated is 10,106.
- Method 2, index: find the matching entries in the index, then go to the table one entry at a time to read the other columns. It reads fewer rows, but each one means jumping to a different place in the table, so the cost per row is higher. MySQL looked into the index and estimated that about 100 rows match the condition, and calculated an estimated cost of 48.
- The optimizer chooses the method with the lower estimated cost: the index.
- Starting from the root of the index (a B-tree), it goes down to a leaf to find the first position that matches the condition. In each page, it narrows the range among the sorted keys. This index has 100,000 entries and its height is 2. Reading 2 pages is enough to get there.
- From that position, it reads along the index to collect the matching entries (100 in all), and for each entry it reads the row from the table. The rows that do not match the condition were never read.
Result of this run
- The lower the share of matching rows (the better the selectivity), the greater the benefit of the index. A full table scan would have had to read 100,000 rows, but the index read only 100. The estimated costs the optimizer calculated are also 10,106 for the full table scan and 48 for the index.
Code
CREATE INDEX idx_orders_amount ON orders (amount);
SELECT *
FROM orders
WHERE amount < 100; -- 0.1% of all rows
Assumptions of this model
All 54 combinations were run on MySQL 8.4.11, with the orders table created anew for each table size, and compared with this lab. amount was spread evenly from 0 to 99,999, so that the condition amount < share × 1,000 matches exactly that share of the rows. The method chosen is the type and key shown by EXPLAIN, and rows read are the Handler_read_% values shown by SHOW SESSION STATUS after the query ran to the end (for a full table scan, Handler_read_rnd_next minus the one last call that detects the end, and for the index, Handler_read_next). The estimated costs and estimated row counts are the values MySQL calculated in the verification environment, rounded to integers and copied as they are. When the index exists, the two costs are the cost of table_scan and of range_scan_alternatives in range_analysis of the optimizer trace, and when there is no index, the cost of the full table scan is query_cost from EXPLAIN FORMAT=JSON. These values changed a little from run to run when the statistics were collected again or when different data was in the buffer pool, and the share from which a full table scan is chosen also depends on the environment. In the verification environment (a 128MB buffer pool), a full table scan was chosen from 30% with 1,000 rows, from 20% with 100,000 rows, and from 10% with 10,000,000 rows. For a wide range, MySQL estimated more matching rows than there really were (38,342 rows for the 20,000 rows that are 20% of 100,000 rows), and with 10,000,000 rows, where the table is larger than the buffer pool, it calculated a higher cost for reading one row through the index. With FORCE INDEX, MySQL 8.4 treats a full table scan as very expensive and also skips estimating the number of rows in the range. The height of the index was checked by reading PAGE_LEVEL of the root page from the data file (1 for 1,000 rows, 2 for 100,000 rows, and 3 for 10,000,000 rows). Execution times were measured once: reading 50% of 10,000,000 rows took about 5 seconds with a full table scan and about 408 seconds with FORCE INDEX, and at 20% it took about 4 seconds and about 9 seconds. The times changed a lot from run to run, depending on the state of the buffer pool. With an equality condition instead of a range condition, the result is different. When an index is created on a status column that has only two values, each in half of the rows, and the query uses status = 'CANCELED', MySQL 8.4 chose the index (type ref), not a full table scan, at all three table sizes. If you select only columns that are in the index instead of SELECT *, the query does not need to go to the table, and the calculation changes. This is covered in the "Composite and covering indexes" lab.
Previous lab: Binary search and B-trees · Next lab: Composite and covering indexes