Handbooks / SQL / Chapter 5
Indexes and Query Plans
7 pages · ~5 min✓ Reviewed
Builds on Window Functions.
SQLPage 1B-tree Index Mental Model
1. Tree and leaves
- Sorted, balanced tree of key values pointing to rows
- Point lookup: O(log n)
- Range scan or
ORDER BY on the key: O(log n + k) for the k rows read
- Rootentry point
- Internal nodesroute by key
- Leaf pageslinked in key order
- Range scan finds the start once, then walks the linked leaves
SQLPage 2Composite and Covering Indexes
1. Order and the Leftmost Prefix
- Index on
(a, b, c) is sorted by a, then b within a, then c within b - Usable from the left only: the leftmost prefix
SQLPage 3When Indexes Are Not Used
1. Predicate hides the column
- Function on the column hides the sorted key
- Leading %:
LIKE 'abc%' is a prefix range; '%abc' is not - Type mismatch: VARCHAR vs number casts every row
SQLPage 4EXPLAIN and Sargable Queries
1. Reading a Plan
EXPLAIN: plan only, query not runEXPLAIN ANALYZE (Postgres, MySQL 8): runs it, adds actual time and rows
SQLPage 5DML and Constraints
1. DML and Index Cost
INSERT INTO t(cols) VALUES (...)UPDATE t SET c = v WHERE ...DELETE FROM t WHERE ...- Run UPDATE and DELETE in a transaction with a WHERE
- INSERT and DELETE touch all indexes; UPDATE touches those with a changed column
- Write-heavy table → keep few indexes
SQLPage 6Indexing and Query Tuning Cheat Sheet
1. Index Design Rule
- Equality colsseek
- ORDER BY colsno sort
- Range collast
- Leftmost prefix: (a,b,c) serves a, a+b, a+b+c, not b alone
- ORDER BY after a range column cannot remove the sort
2. Why an Index Is Skipped
- Function on column:
YEAR(d) = 2025 - Leading
%: LIKE '%x'
An index on (country, city, age) and the query WHERE country = 'IN' AND age = 30. How much of the index narrows the seek?
- Only country, the leftmost prefix.
city is skipped, so age is only checked on the entries read.
phone is an indexed VARCHAR. Spot the bug: WHERE phone = 5551234.
- MySQL, SQL Server: the column is cast on every row, so the index is skipped.
- PostgreSQL: it fails with
operator does not exist: character varying = integer. - Fix: compare with a string,
'5551234'.