Indexes, including B-tree, composite, partial, GIST and GIN
How indexes work internally, the leftmost-prefix rule, partial and expression indexes, spatial GIST and array GIN indexes from Hostel, and the cost every index adds to writes.
The concept
Without an index, WHERE email = ? reads every row (a sequential scan). An index is a separate sorted data structure that points to rows, so lookups take O(log n).
B-tree (the default)
A balanced tree of sorted keys. It supports =, <, >, BETWEEN, ORDER BY, LIKE 'abc%' (prefix only) and IS NULL.
Composite indexes and the leftmost-prefix rule
CREATE INDEX idx_bookings_room_period_status
ON bookings (room_id, academic_year, semester, status);
The index is sorted by room_id, then academic_year, and so on, like a phone book (last name, then first name). It helps:
WHERE room_id = ?✅WHERE room_id = ? AND academic_year = ?✅WHERE room_id = ? AND academic_year = ? AND semester = ? AND status = ?✅WHERE academic_year = ?❌ (it skips the leading column)
Column order rule of thumb: equality columns first, then the range or sort column. Put the more selective column first when both are equalities.
Partial index: index only the rows you query
CREATE INDEX idx_bookings_payment_due ON bookings (payment_expires_at)
WHERE status = 'APPROVED' AND payment_expires_at IS NOT NULL;
This is smaller and faster, and it fits a known hot query exactly: the expiry sweeper.
Other index types (Postgres)
| Type | Use | Your project |
|---|---|---|
| GIST | Geometry, ranges, nearest-neighbour | Hostel hostels.location (PostGIS) |
| GIN | Arrays, JSONB, full-text (tsvector), trigram |
Hostel student_preferences.tags |
| BRIN | Huge, naturally ordered tables (time-series) | Candidate for audit logs |
| Hash | Equality only | Rarely worth it |
| Expression | CREATE INDEX ON users (lower(email)) |
Would help Store’s upper(email) query |
Covering (INCLUDE) |
Index-only scans | (company_id, entry_date) INCLUDE (amount) |
In your projects
db/changelog/scripts/index.sqlCREATE INDEX idx_hostels_location ON hostels USING GIST (location);
CREATE INDEX idx_landmarks_location ON landmarks USING GIST (location);
CREATE INDEX idx_student_preferences_tags ON student_preferences USING GIN (tags);
CREATE INDEX idx_hostels_is_active ON hostels (is_active) WHERE is_active = TRUE;
-- "Backs the countReservedBeds query"
CREATE INDEX idx_bookings_room_period_status ON bookings (room_id, academic_year, semester, status);Each index has a comment saying which query it serves, which is a great habit.
scripts/009-ledger.sqlTenant-first composite indexes, idx_journal_company_date (company_id, entry_date), because every query is scoped by company_id. Also partial unique indexes: uq_journal_idempotency ... WHERE idempotency_key IS NOT NULL and uq_journal_one_reversal (an entry can be reversed at most once).
initial-schema.sqlCREATE INDEX idx_products_category_id ON products (category_id); with the comment “PostgreSQL does not automatically index foreign keys”. Correct, and many developers don’t know it.
scripts/index.sql (24 indexes)RM’s 24 indexes include FK indexes like idx_users_unit_id ON users(unit_id). IR3D adds -010-blocked-users-partial-unique and other partial unique indexes.
The costs
- Every index slows INSERT, UPDATE and DELETE, since each one must be maintained.
- Every index uses disk and RAM. Unused indexes are pure cost, so find them with
pg_stat_user_indexes.idx_scan = 0. - Low-selectivity columns (a boolean that is true 50% of the time) rarely benefit, except as a partial index on the rare value. That’s why Hostel’s
is_activeindex usesWHERE is_active = TRUE.
How to verify an index is used
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM bookings WHERE room_id = '...' AND academic_year = '2026/2027';
-- look for: Index Scan using idx_bookings_room_period_status
-- versus: Seq Scan on bookings (bad on big tables)
The bonus module has a full lesson on reading query plans.