Reading every page
A huge book has its pages in no particular order. To find every mention of "Zoe" you'd have to turn every page, from start to finish, and even after finding her you'd keep going in case she appears again.
Full table scans
Rows are stored roughly in insertion order. A query like WHERE email = 'zoe@x.io' on an unindexed column needs a
full table scan (Postgres calls it Seq Scan): read every row and test it. That's fine for a thousand rows and painful
for fifty million, and it gets slower as the table grows.
The index at the back
A book's index is sorted, so you never read it all. Is "Zoe" in AโM or NโZ? NโZ. Then the right page of the index, which says "page 3". Turn straight there. A few looks instead of thousands of pages.
B-trees
Most indexes are B-trees: balanced trees of sorted keys, each node one disk page holding hundreds of keys. A lookup
walks from the root to a leaf, typically 3โ4 page reads even for hundreds of millions of rows (O(log n)). Leaves point
to the row and are linked in order, so ranges (BETWEEN, >, ORDER BY) are fast too.
1CREATE INDEX idx_users_email ON users (email);Primary keys and UNIQUE constraints get an index automatically. Foreign keys often don't, and usually should.
Indexes have a cost
Every new page means updating every index too, so too many indexes slow down writing. And an index sorted by town, then age, helps you find "people in Leeds aged 30", but not "everyone aged 30".
Trade-offs and composite indexes
Every index costs disk space and slows INSERT, UPDATE and DELETE. Add indexes for the queries you actually run.
A composite index on (city, age) is sorted by city, then age within each city. It serves filters on city, or on
city and age, but not age alone (the leftmost-prefix rule). Put equality columns first, then range columns.
Check with EXPLAIN ANALYZE. Wrapping a column in a function (WHERE lower(email) = โฆ) skips a plain index unless you
index that expression.
Covering indexes contain every column a query needs (INCLUDE in Postgres), so the table isn't touched at all.
Other kinds: hash indexes for equality only, GIN for full-text and JSON, GiST for geometry, and LSM trees in write-heavy stores like Cassandra and RocksDB.