Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 149/ 160
08. Backend

Database Indexing

B-tree and specialized indexes that keep lookups fast as tables grow.

IntermediateB-Tree · Composite3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

An index is like a sorted table of contents for your data, so the database can jump straight to the rows you ask for instead of reading everything.

Think of it like…

The index at the back of a textbook. Instead of reading every page to find "attention", you look it up alphabetically and jump to the page numbers; the index costs extra pages and must be updated whenever the book changes, so you only index terms people actually look up.

Where you’ve seen it

The messages table has 50 million rows at about 1.5 KB each, around 75 GB. The history query is WHERE conversation_id = $1 ORDER BY created_at DESC LIMIT 20. With no index the planner sequentially scans all 75 GB, which at a few hundred MB to a few GB per second takes tens of seconds, and it gets worse every week. A B-tree index with 8 KB pages holds roughly 500 entries per page, so a three-level tree addresses 500 × 500 × 500 = 125 million rows; finding the start of a conversation costs three or four page reads and the next 20 entries sit side by side in a leaf. The composite index (conversation_id, created_at DESC) serves both the filter and the sort without a separate sorting step, and runs in about a millisecond when pages are cached. The index itself needs about 50 million × 24 bytes ≈ 1.2 GB, small beside the 75 GB table. Order matters: an index on (created_at, conversation_id) would not help the equality filter, and the leftmost-prefix rule means (tenant_id, created_at) serves queries on tenant_id alone or both columns, but not created_at alone. For the job queue, a partial index ON jobs (run_at) WHERE status = 'queued' stays tiny because finished jobs, the vast majority, aren't in it. A jsonb column of tool metadata gets a GIN index only after the team confirms a real query filters on it. Each additional index slows every insert, so the team caps them per table, drops unused ones found in pg_stat_user_indexes and checks every new query with EXPLAIN (ANALYZE, BUFFERS) to confirm an index scan rather than a sequential scan. Vector search uses an HNSW index on the embeddings column with a tuned recall and latency trade-off.

Words you’ll hear

B-tree
A balanced, sorted tree that finds a key in a few page reads.
Composite index
An index over several columns, ordered by the first column, then the next.
Covering index
An index that contains every column a query needs, avoiding table access.
Selectivity
How sharply a condition narrows the rows; high selectivity favours an index.

Visual diagram

Loading interactive diagram

Theory & deep dive

How B-tree indexes work and how to design them

A B-tree stores keys in sorted order across pages (commonly 8 KB). Internal pages route to children; leaf pages hold the keys with row pointers and are linked for range scans. With about 500 entries per page the tree stays shallow: 500³ = 125 million rows at three levels, so a lookup costs a handful of page reads and the top levels stay cached in memory. That is why an equality lookup or a short range is nearly independent of table size, while a sequential scan grows linearly with it.

Design indexes from queries. For WHERE conversation_id = ? ORDER BY created_at DESC LIMIT 20, the index (conversation_id, created_at DESC) finds the conversation, then reads the newest 20 entries in order with no sort. Put equality columns first, then the range or sort column. The leftmost-prefix rule means an index on (tenant_id, created_at) helps queries that filter by tenant_id or by both, not by created_at alone. Covering indexes (INCLUDE (role, token_count) in PostgreSQL) let the planner answer from the index without touching the table. Partial indexes (WHERE status = 'queued') stay small when the interesting rows are a small fraction. Prefer high-selectivity columns; an index on a boolean flag that splits rows 50/50 rarely helps.

Capacity of the tree

8 KB page, about 500 entries per page. Level 1: 500 pointers; level 2: 500² = 250,000; level 3: 500³ = 125,000,000. Messages table of 50 million rows → three levels. Index size ≈ 50,000,000 × 24 B ≈ 1.2 GB (plus page overhead), versus 75 GB for the table.

Key takeaway: Index for the actual queries: equality columns first, then sort or range columns, using covering and partial indexes where they pay off.

Costs, maintenance and specialised indexes

Every index must be updated on each INSERT, UPDATE of an indexed column and DELETE, so five indexes on a hot table can multiply write cost and I/O and enlarge the working set that must fit in memory. Indexes also bloat after many updates and deletes, need occasional REINDEX or vacuum attention and consume storage (the example index is about 1.2 GB). Keep only indexes that queries use: check usage statistics (pg_stat_user_indexes), drop duplicates (an index on (a) is redundant when (a, b) exists) and add new ones concurrently (CREATE INDEX CONCURRENTLY) to avoid blocking writes. Verify each new query with EXPLAIN (ANALYZE, BUFFERS): you want an index or index-only scan with a small number of buffers, not a sequential scan, and estimated row counts that match reality (stale statistics lead to bad plans; run ANALYZE).

Specialised types cover other shapes. GIN indexes make jsonb containment and full-text search fast but are slower to update. Hash indexes serve pure equality. BRIN indexes are tiny and suit huge, naturally ordered append-only tables (time-series traces). Vector indexes (HNSW, IVFFlat in pgvector) accelerate approximate nearest-neighbour search with a recall-versus-latency trade-off you tune and measure. Unique and foreign-key constraints create or need indexes; index foreign-key columns that you join or delete by. At very large scale, combine indexing with partitioning (by tenant or month) so that queries touch only relevant partitions and old data can be dropped cheaply.

Partial index size

jobs table: 20,000,000 rows, 2,000 queued at any moment. Full index on run_at: 20,000,000 entries (~480 MB). Partial index WHERE status = 'queued': about 2,000 entries (~50 KB), always cached and cheap to maintain, and exactly what the worker polls.

Key takeaway: Indexes trade write cost and storage for read speed; measure with query plans, prune unused ones and use specialised types for JSON, time-series and vectors.

How it works, step by step

Step 1 of 4
Backend engineer

1. List the hot queries

Collect the slowest and most frequent queries from logs or pg_stat_statements with their filters and sort orders.

history · job polling · usage by tenant
Key numbers at this step
Target
p95 latency

When to use it & trade-offs

What it is

An index is an auxiliary data structure that lets the database find rows without scanning the whole table. The default is a B-tree: a balanced, sorted tree whose pages hold hundreds of keys, so a lookup visits only a handful of pages regardless of table size and range scans read neighbouring entries in order. A composite index orders rows by several columns, so the order of columns matters (the leftmost-prefix rule); a covering index includes extra columns so the query never touches the table (an index-only scan); a partial index covers only rows matching a condition. Specialised types exist for other shapes: GIN for jsonb and full-text search, HNSW or IVFFlat for vector similarity. Indexes speed reads and cost writes, storage and maintenance.

Why it matters: AI backends accumulate tables fast: messages, traces, job records, embeddings, usage events. A query that took 5 ms with 10,000 rows can take tens of seconds at 50 million without the right index, and the slowdown arrives suddenly as data grows. Over-indexing is the opposite failure, with every insert maintaining six structures and storage doubling. Reading query plans and indexing for real access patterns keeps latency predictable and writes cheap.

When to reach for it

  • Composite indexes for history, usage and job queries
  • Partial indexes for queues and status-filtered rows
  • GIN or vector indexes only after confirming the queries

When to avoid or be careful

  • Indexing every column in advance
  • Low-selectivity indexes such as a boolean flag
  • Creating large indexes without CONCURRENTLY on a live table

Index types in PostgreSQL

B-tree
Best for: Equality, ranges and sorting

Strengths: General-purpose; supports ordering.

Watch out: Each index slows writes.

GIN
Best for: jsonb containment and full-text search

Strengths: Fast multi-value lookups.

Watch out: Larger and slower to update.

BRIN
Best for: Huge append-only time-ordered tables

Strengths: Tiny index.

Watch out: Coarse; needs natural ordering.

HNSW (pgvector)
Best for: Approximate nearest-neighbour vector search

Strengths: Fast similarity queries.

Watch out: Approximate recall; memory-heavy build.

Interview signals & numbers to know

When this topic comes up

  • “This query got slow as the table grew”
  • Composite index column order
  • Covering and partial indexes
  • Reading EXPLAIN output
  • Write cost of too many indexes

Benchmarks & rules of thumb

500³ = 125M -
rows addressed by a three-level B-tree with ~500 entries per page
≈ 75 GB vs 1.2 GB -
50M-row table versus its composite index
3–4 page reads -
to find the start of a conversation's history

Common mistakes & follow-ups

Common interview mistakes

  • Putting the range column before the equality column.
  • Never checking whether an index is actually used.
  • Stale statistics causing the planner to ignore a good index.

Likely interviewer follow-ups

  • How would you index the messages table for history and for usage reports?
  • What does a covering index buy you?
  • How do you add an index to a busy production table safely?
Interview tip: Show the page arithmetic (three levels cover 125 million rows); it explains why indexed lookups barely slow down as tables grow.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Database Indexing with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
SQL vs NoSQL
Next topic
Transactions and ACID