Indexes and query performance
Make reads fast by avoiding full scans, and understand what indexes cost on writes.
14 min readWhy full scans hurt
Without an index, a query such as finding all orders for user 42 must read every row in the table and check it. On 1 000 rows that is instant; on 100 million rows it reads gigabytes and takes seconds, while competing for disk and CPU with every other query. Worse, the cost grows with the table, so a query that was fine at launch becomes the outage a year later. Most database performance problems in young systems are missing indexes, not a lack of hardware.
How a B-tree index works
The common index is a B-tree: a sorted, balanced tree of keys with pointers to rows. Because it is sorted and shallow, finding one key in 100 million takes only three or four page reads, usually from memory. Sorted order also makes range queries cheap, such as created_at between two dates, and lets the database return rows already ordered, which is exactly what cursor pagination needs. Hash indexes support only equality lookups, and specialised indexes exist for full-text search and geospatial queries.
- Equality lookup: WHERE email = ?
- Range scan: WHERE created_at > ? ORDER BY created_at LIMIT 20
- Composite index (user_id, created_at): one user's items, newest first
Composite indexes and column order
A composite index sorts by its first column, then by the second within each value of the first, like a phone book sorted by surname then first name. An index on (user_id, created_at) serves a query for one user's recent posts perfectly, but it cannot help a query that filters only by created_at. Design indexes from your actual queries: put equality filters first and the range or sort column last. Check the query plan with EXPLAIN to confirm the database uses the index you expect.
Indexes are not free
Every index is a separate structure the database must update on each insert, update or delete, and it takes disk and memory. A table with eight indexes does nine writes for every row inserted. For read-heavy data this is a good trade; for write-heavy tables, such as an event log ingesting 20 000 rows per second, keep indexes to the few that queries truly need. Unique indexes double as correctness tools: they enforce rules such as one account per email or one vote per user, even under concurrent requests.
Key takeaways
- Missing indexes turn queries into full scans whose cost grows with the table
- B-tree indexes make equality and range lookups take a handful of page reads
- Order composite index columns as equality filters first, then range or sort
- Each index slows writes and uses memory, so index for real queries only
Sign in to track lessons and earn badges.