An index is a data structure that lets the database find rows without scanning the whole table, much like a phone's contact list sorted by name: you jump to "M" for Maya instead of scrolling through every contact. When you sketch a schema in an interview, call out which columns are indexed and why.
Start from the queries#
Pick indexes by starting from your most important queries, not from the table. For an online course platform, each common query maps to an index:
| Query | Index |
|---|---|
| All lessons in a course | lessons(course_id) |
| Newest courses first | courses(created_at) |
| A student's courses, most recent first | Composite enrollments(student_id, enrolled_at) |
The last row is the interesting one. Here's that composite index and the query it serves:
CREATE INDEX idx_enrollments_student_enrolled
ON enrollments (student_id, enrolled_at DESC);
-- Served by the composite index:
-- filter on student_id, already sorted by enrolled_at
SELECT course_id FROM enrollments
WHERE student_id = 42
ORDER BY enrolled_at DESC
LIMIT 20;
Column order matters in a composite index. (student_id, enrolled_at) helps queries that filter on student_id, with or without enrolled_at. It doesn't help a query that filters only on enrolled_at.
The trade-off#
Indexes aren't free, which is why you only add the ones your queries need. Every index speeds up some reads but adds work to every insert and update, because the index has to be updated too. It also takes storage. Index the columns your key queries filter, join or sort on, and skip the rest. In a write-heavy system, dropping unused indexes is one of the cheapest wins (see Scaling Writes).
In an interview#
The same rule, start from the query, is what interviewers listen for. Tie each index to the endpoint that needs it. Saying "GET /students/{id}/courses looks up enrollments by student_id, so that column gets an index" tells the interviewer your indexes come from real queries, not guesswork.
Key takeaways#
- An index trades extra write work and storage for much faster lookups.
- Choose indexes from your access patterns, not from the schema alone.
- A composite index serves queries that use its leading column(s).
- Name the endpoint each index supports.