Database indexing in system design
A database index is a separate, sorted structure that lets the database find rows by a column's value without scanning the whole table, much like the index at the back of a book. Most indexes are B-trees, which make lookups and range queries take a handful of page reads even on huge tables. The cost is that every insert, update and delete must also update each index, so in a design interview you add indexes for the queries the product actually runs and say what they cost on writes.
By Evin JohnPublished 7 min read
1. What an index is
Without an index, finding all orders for customer 42 means reading every row and checking it. An index on customer_id keeps the values sorted alongside a pointer to each row, so the database can jump straight to 42 and read only its entries. The primary key usually has an index automatically; in many engines (InnoDB, SQLite rowid tables, clustered indexes in SQL Server) the table itself is stored in primary key order. Every other index is a secondary index pointing back to the row.
2. Why interviewers ask about it
Once you draw a database and write a schema, the next question is "how does this query stay fast at a billion rows?" Indexing is the first answer, before caching or sharding. Interviewers listen for whether you index the access patterns you named, know the composite index rules, and remember that indexes slow writes. In data-heavy prompts they may also ask about full-text, geospatial or time-series lookups, which need different index types.
3. How indexes are built
| Structure | How it works | Good at | Weak at |
|---|---|---|---|
| B-tree (B+tree) | A wide, shallow balanced tree of pages; leaves hold sorted keys | Equality, ranges, ORDER BY, prefix matches | Very high random write rates on slow disks |
| Hash index | Hash of the key to a bucket | Exact-match lookups | Ranges and sorting; not usable for <, >, BETWEEN |
| LSM tree | Writes go to memory, then to sorted immutable files merged in the background | Heavy write throughput (many NoSQL and time-series stores) | Reads may check several files; compaction uses disk and CPU |
| Inverted index | Each word maps to the list of documents containing it | Full-text and tag search | Frequent updates to large documents |
| Geospatial (R-tree, geohash, S2-style cells) | Groups nearby points or shapes | "Within 2 km" and bounding-box queries | Exact equality on other columns |
| Bitmap | One bit array per distinct value | Low-cardinality columns in analytics | Frequent row-level updates |
| Vector (approximate nearest neighbor) | Graph or cluster structures over embeddings | Similarity search for recommendations and semantic search | Exact answers; results are approximate |
A B-tree with a few hundred keys per page is only three or four levels deep even for hundreds of millions of rows, and the upper levels usually sit in memory. That is why an indexed lookup costs a handful of page reads regardless of table size.
4. Composite and covering indexes
A composite index sorts by the first column, then by the second within each first value, like a phone book sorted by last name then first name. That gives the leftmost-prefix rule: an index on (customer_id, created_at) helps queries that filter on customer_id, or on customer_id and created_at, and it can return one customer's orders already sorted by date. It does not help a query on created_at alone. A covering index contains every column a query needs, so the database never visits the table.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INT,"
" status TEXT, created_at TEXT, total INT)")
# ... insert 200,000 rows ...
plan = lambda sql: [r[3] for r in db.execute("EXPLAIN QUERY PLAN " + sql)]
q = "SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20"
plan(q) # ['SCAN orders', 'USE TEMP B-TREE FOR ORDER BY']
db.execute("CREATE INDEX idx_cust_created ON orders (customer_id, created_at)")
plan(q) # ['SEARCH orders USING INDEX idx_cust_created (customer_id=?)']
plan("SELECT * FROM orders WHERE created_at = '2026-03-04'")
# ['SCAN orders'] second column alone: index not usable
plan("SELECT created_at FROM orders WHERE customer_id = 42")
# ['SEARCH orders USING COVERING INDEX idx_cust_created (customer_id=?)']
plan("SELECT * FROM orders WHERE customer_id + 0 = 42")
# ['SCAN orders'] an expression on the column hides it from the index- Column order matters. Put equality filters first, then the range or sort column.
- Selectivity matters. An index on a column with two values (paid, refunded) rarely helps on its own; the planner may prefer a scan. It can still help as a later column in a composite index or as a partial index on the rare value.
- Expressions hide columns. Wrapping a column in a function or arithmetic usually prevents index use unless you index that expression.
- Check the plan. Every relational database has EXPLAIN; mention it when asked how you would verify an index is used.
5. What indexes cost
Each secondary index is another structure to update on every write that touches its columns. Five indexes can mean roughly six writes per insert, plus more disk, more memory for the hot pages, and slower bulk loads. Unique indexes also enforce constraints, which is useful (one booking per seat) but adds a check to every insert. For write-heavy tables, keep indexes few; for read-heavy ones, index the important queries generously. Unused indexes are pure cost: most databases can report which indexes are never read.
6. Indexes in sharded and replicated systems
When data is sharded by one key, a secondary index has two shapes. A local index lives on each shard and covers only that shard's rows, so a query on the secondary column must ask every shard. A global index is itself partitioned by the indexed value, so the query goes to one place, but each write must update a different shard asynchronously or in a distributed transaction. Our sharding guide covers this trade-off. Indexes are also built separately on replicas in some setups, which lets an analytics follower carry indexes the primary does not need.
7. How it shows up in common prompts
| Prompt and query | Index | Note |
|---|---|---|
| URL shortener: redirect by code | Primary key or unique index on short code | Point lookup; also cached |
| Twitter: a user's latest posts | Composite (user_id, created_at) | Serves the filter and the sort together |
| Uber: drivers near a rider | Geospatial index or geohash cells | B-tree on latitude alone cannot do "nearby" |
| Search autocomplete: prefixes | Trie or prefix index over normalized terms | Ranked by popularity per prefix |
| Ticket booking: one seat per show | Unique index on (show_id, seat_id) | The index enforces the business rule |
| Job scheduler: due jobs | Composite (status, run_at), or partial index on pending jobs | Workers poll the smallest due run_at |
8. Mistakes to avoid
- "Index every column." Writes slow down and most indexes are never used.
- Wrong composite order. (created_at, customer_id) does not serve "orders for customer 42" well.
- Assuming NoSQL means no indexes. Key-value stores give you one index, the key; everything else you design yourself.
- Using a B-tree for text search or geography. Name the right index type.
- Forgetting the write side of a global secondary index in a sharded design.
9. How to talk about it in the interview
- List the top queries first, then give each one an index, with column order.
- Say which index is unique and which business rule it enforces.
- Estimate the write cost if the table is write-heavy.
- For sharded data, say whether secondary indexes are local or global.
Fictional example
- Interviewer
- Agents see open tickets for their team, newest first, and customers see their own tickets. What indexes?
- Candidate
- Two queries, two indexes. For agents, a composite index on (team_id, status, created_at), with equality columns first and the sort column last. For customers, (customer_id, created_at).
- Interviewer
- Status has only four values. Is it worth indexing?
- Candidate
- Not alone, but inside the composite it narrows each team to open tickets. Since most tickets end up closed, a partial index on open tickets only would be smaller and faster where the database supports it.
- Interviewer
- And full-text search over ticket bodies?
- Candidate
- That needs an inverted index, either the database's full-text feature or a search engine fed from the change log.
Practicing with Natively
Indexing answers sound confident until the interviewer asks about column order or write cost. During a practice session, Natively transcribes the conversation and can suggest talking points per question, which helps you catch afterwards whether you tied each index to a real query. It can read a screenshot of a schema or an EXPLAIN plan and explain it. The transcript and notes are saved so you can listen back to the weak spots.
Questions people ask
How does a database index work?
It keeps a column's values sorted in a separate structure, usually a B-tree, with pointers to the rows. The database walks a few levels of the tree to find matching values instead of scanning every row.
What is the leftmost prefix rule for composite indexes?
An index on (a, b) is sorted by a first, then by b within each a. It can serve queries on a, or on a and b, and return results sorted by b for one a, but it cannot efficiently serve a query on b alone.
What is a covering index?
An index that contains every column a query needs, so the database answers the query from the index without reading the table rows.
Why not index every column?
Every index must be updated on each insert, update or delete that touches its columns, and each takes disk and memory. Unneeded indexes slow writes and add cost without speeding any real query.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
