What indexing strategies improve database performance?
107 views
51 of 106
1
The problem
Question presented to candidate:
"Your API has a slow endpoint and the database is the bottleneck. Beyond 'add an index', what indexing strategies would you use? How do you decide which columns go in an index and in what order, and how do you know you have too many?"
What a strong answer should cover:
Start from the workload: find the slow, frequent queries (pg_stat_statements, slow query log) and read the plan with EXPLAIN ANALYZE before and after
Composite indexes and the leftmost-prefix rule: equality columns first, then the range or sort column; PostgreSQL 18 adds skip scan for some queries that omit the leading column
Covering indexes (INCLUDE, PostgreSQL 11+) enable index-only scans; partial indexes index only the rows you query; expression indexes for lower(email)-style predicates
Selectivity: the planner skips an index that matches a large share of rows, because random page reads cost more than a sequential scan
Specialised types where they fit (GIN for jsonb, arrays and full-text; BRIN for huge append-only time-ordered tables; hash for equality only)
Every index taxes writes and memory: measure usage and drop unused or duplicate indexes
Clarifying questions expected:
Which exact queries are slow, and how often do they run compared with writes to the table?
Is this OLTP traffic (many small queries) or reporting (few large scans)?
Code / implementation expected: Optional โ CREATE INDEX statements with reasons are enough; the example counts the work each index design costs on one table.
indexing
database
2
Try it yourself
Sketch your approach before you read the solution. That is what the interview tests.
Stuck? Get a hint.
A short nudge toward the approach. It will not give the answer away.
3
Solution
Target Audience: Developers who know what an index is and want to choose good ones. If "B-tree", "page" and "leaf" are new, read Explain database indexing and B-trees first; this page does not re-explain the tree.
Difficulty: Medium
Verified with: Node 22.22 and Python 3.12 (both print identical output), plus real query plans from SQLite 3.45.1 via Python.
How to read this doc: Every idea is explained in plain language first, then tagged with ๐ Interview term: so you also learn the exact words an interviewer expects. Behaviour shown comes from running the example; the Verified section quotes the full output.
1. Why This Even Matters โ A Story First
A warehouse keeps its parcels on shelves in arrival order. The manager adds a printed list sorted by customer name. Great for "all parcels for Lee". Then someone as
The solution is hidden so you can try first
15 min read ยท 9 sections
4
Read the code
Index designs compared: composite order, covering, partial, skip scan and selectivity