Performance · mid
Indexes: B-trees, composite and covering indexes
An index is a separate sorted structure (usually a B-tree) that lets the database find rows by a key in a few steps instead of scanning the table, and a composite index helps only queries that use its leading columns, so column order matters.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- B-tree: sorted keys with pointers to rows; lookup, range scans and ORDER BY on the indexed columns are fast (logarithmic). Primary keys and UNIQUE constraints create indexes automatically; foreign keys do not in Postgres: index them yourself.
- Composite index (a, b): works for WHERE a = ?, WHERE a = ? AND b = ?, WHERE a = ? ORDER BY b; usually not for WHERE b = ? alone (the phone book is sorted by surname first). Put equality columns first, then range or sort columns. Postgres 18 can sometimes 'skip scan' a missing leading column, but do not design around it.
- Covering index: the index holds every column the query needs, so the table is not touched (index-only scan); Postgres can add payload columns with INCLUDE.
- Indexes stop working when you wrap the column: WHERE lower(email) = ? needs an expression index on lower(email); LIKE '%x' cannot use a B-tree; type mismatches can block them too.
- Partial index: CREATE INDEX ... WHERE status = 'pending' for a small hot subset; unique partial index enforces 'one active row per user'.
- Costs: every index slows INSERT/UPDATE/DELETE and uses disk and memory. Index for real query patterns; remove unused ones.
- Low-selectivity columns (a boolean with 50/50 values) rarely benefit from a plain index.
The red pen
Common traps: mistake → fix
Mistake: Index every column
Fix: writes get slower and the planner still uses only what helps.
Mistake: An index on (a, b) also serves queries on b
Fix: it serves queries on the leading column(s); b alone usually needs its own index.
Mistake: My column is indexed so WHERE lower(email) = ? is fast
Fix: the function hides the column; use an expression index.
Easy to hard
Questions interviewers ask, easy to hard
- What is an index and how does a B-tree make lookups fast?
- Why not index every column?
- We have an index on (city, rating). Which queries use it? Which do not?
- What is a covering index?
- WHERE lower(email) = ? is slow even though email is indexed. Why?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.