3.1 Without an Index: Full Scan
When there is no index, all the database can do is read every page of the table from beginning to end. This is called a full scan. If there are 1 million data pages, all 1 million must be read. As seen in Chapter 1, reading one page from disk and loading it into the buffer pool is an expensive operation. A full scan that reads pages in bulk also pushes frequently used pages out of the buffer pool, so they have to be read from disk again. This hurts database performance. Even if only a single row matches the condition, the cost does not change.
Figure 3-1. Lookup with a full scan and with an index
flowchart LR
Q["Query<br/>WHERE customer_id = 1002"]
subgraph FS ["Full scan"]
direction TB
P1["Data page 1"] --> P2["Data page 2"] --> P3["Data page 3"] --> PN["… Data page N"]
end
subgraph IX ["Index lookup"]
direction TB
I1["Index<br/>sorted by customer_id"] -->|"Find the location of 1002"| D1["That one data page"]
end
Q -->|"No index"| P1
Q -->|"Index exists"| I1
The upper path is the case without an index. Rows are stored in the data pages in no particular order, so to find one customer number the database must read every page from page 1 to the last page N and compare each row against the condition. Even if the row sought is in the first page, other pages may hold more rows with the same value, so it reads to the end.
The lower path is the case with an index. The index is sorted by customer_id, so it can go straight to where 1002 is, check the location recorded there, and then read only the one data page it needs. The difference between the two paths is the number of pages read, that is, the difference in disk I/O and buffer pool usage.
For this reason, indexes are created in advance for frequently used lookup patterns. If rows are often looked up by customer number, create an index sorted by customer number; if they are often looked up by order date, create an index sorted by date. Because an index is sorted, it can go straight to the neighborhood of the desired value.