8. Performance: Index Internals & B-Trees
The 100ms Goal
Building a database that works with 1,000 rows is easy. Building one that works with 100 million rows is Engineering. In this module, we explore how Postgres actually finds your data and how to use Indexes to turn minutes into milliseconds.
The B-Tree Index: Under the Hood
By default, Postgres uses a B-Tree (Balanced Tree) index. Instead of reading every row (O(N)), it traverses a tree (O(log N)). For 1 million rows, a B-Tree only needs about 20 comparisons to find your record.
INSERT, UPDATE, and DELETE slower because the database has to update the tree structure. Never index columns you don't frequently search by.Advanced Index Types
Sometimes a B-Tree isn't enough.
Best for searching inside JSONB objects or arrays. It allows you to query Does this array contain X?.
For massive, time-sorted tables (billions of rows). It uses 1% of the RAM of a B-Tree but is only efficient if the data is stored in physical order.
Only index some rows: WHERE active = true. Saves massive disk space and RAM.
-- Creating a high-performance GIN index on JSONB CREATE INDEX idx_user_metadata ON users USING GIN (metadata);
Step-by-Step: Performance Debugging
- Identify: Use
pg_stat_statementsto find queries taking > 500ms. - Analyze: Run
EXPLAIN ANALYZEto see if it's doing a Seq Scan. - Monitor: Check
pg_stat_user_indexesto see if your index is actually being used. - Harden: Use
CREATE INDEX CONCURRENTLYin production to avoid locking your table!
Knowledge Check
Ready to test your understanding of 8. Performance: Index Internals & B-Trees?