Two hundred million users, one login query#
SELECT id, password_hash
FROM users
WHERE email = ?;Inspecting the whole table for every login is unacceptable. An index maintains extra data that gives this query a faster path to matching rows.
B-tree intuition: searchable order#
A B-tree-style index keeps keys in a searchable order, supporting equality, range conditions, and ordered traversal. Interview depth means explaining why order helps - not implementing page splits or calculating exact disk operations.
A composite index serves a query shape#
CREATE INDEX messages_conversation_created
ON messages(conversation_id, created_at);
SELECT * FROM messages
WHERE conversation_id = ?
ORDER BY created_at DESC
LIMIT 50;The leading conversation key narrows the data; creation time provides order within that conversation. (created_at, conversation_id) is not equivalent for every query. Exact prefix and ordering rules depend on the database and index type.
Selectivity and specialized paths#
| Index | Purpose | Question |
|---|---|---|
| Primary / unique | Identity or uniqueness | Which invariant is enforced? |
| Composite | Multi-column filter/order | Does column order match the query? |
| Partial | Only rows matching a predicate | Will the query imply that predicate? |
| Covering | Contains additional query columns | Is extra index size/write work justified? |
| Inverted | Terms or tokens to matching documents | Is this a search workload rather than ordered lookup? |
An email is usually selective. country = 'US' may match most rows in a mostly-US dataset, so scanning another access path may cost less than using that index.
- Saying “add an index” without naming the query.
- Ignoring slower writes, storage, maintenance, and write amplification.
- Adding many overlapping indexes “just in case.”
- Assuming an index will be used when the filter/order does not match it.
Use these prompts to extend the design. The useful answer is a reasoned change, not a memorized sentence.
- What happens to write throughput as indexes increase?
- Which composite column comes first?
- Why might the database still scan?
- When does full-text search need an inverted index?
Related practice problems
Use the manifest-backed prompts below to apply this lesson in a complete design.
- PostgreSQL indexesPostgreSQL Documentation