DEV Community

designbench.dev
designbench.dev

Posted on Originally published at designbench.dev

Database indexes for system design interviews: B+trees, column order, and when the planner ignores you

The interview question: "This query was fast at launch and now takes seconds: show a customer's 20 most recent orders. What index would you add, and what does it cost?"

"Add an index on customer_id" is half an answer. Interviewers want to hear why an index is fast, which column order to choose, when the database will ignore your index, and what every index costs on writes. Here is the walkthrough, round by round, with numbers from the Designbench indexes lesson.

Round 1: Why it got slow

Interviewer: Why was it fine at launch?

You: Without an index, the database reads every page of the table and checks every row. At 10,000 rows that is about 100 pages and a couple of milliseconds, so nobody notices. The cost grows with the table, not with the result: at 10 million rows the same query reads 100,000 pages to return 20 rows.

Round 2: What an index actually is

Interviewer: How does an index make it fast?

You: Most databases use a B+tree. Each node is one disk page. Upper pages hold only signposts; every key lives in a leaf, and leaves are linked left to right so range scans just walk along them.

The magic is the fan-out. An 8 KB page holds roughly 300 keys, so:

  • 300 keys fit in 1 level, 90,000 in 2, 27 million in 3.
  • A billion rows needs only 4 levels. A lookup reads 4 index pages plus 1 table page, instead of about 10 million pages for a full scan.

The top levels are tiny and stay in memory, so in practice a lookup costs one or two disk reads.

Round 3: Column order in a composite index

Interviewer: You have an index on (country, city, created_at). Which queries can use it?

You: A composite index is sorted by the first column, then the second within it, then the third, like a phone book sorted by last name, then first name. So it helps any query that filters on a leftmost prefix:

  • WHERE country = 'IN': yes, seeks on country.
  • WHERE country = 'IN' AND city = 'Pune': yes, seeks on both.
  • Same, plus ORDER BY created_at DESC LIMIT 20: yes, and better. Rows are already in created_at order inside that prefix, so the database reads 20 entries and stops. No sort.
  • WHERE city = 'Pune': no. Without country, the matching cities are scattered across the whole index.
  • WHERE country = 'IN' AND created_at > '2026-10-01': partly. It seeks on country, then has to check created_at entry by entry because city sits in between.

The rule to say out loud: equality columns first, then the range or sort column.

For the orders query:

-- In production, build it without locking writes
CREATE INDEX CONCURRENTLY idx_orders_customer_created
    ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, total_cents, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;
-- Expect: Index Scan using idx_orders_customer_created, and no Sort node
Enter fullscreen mode Exit fullscreen mode

And the same intent from a Spring Boot service, with the index declared on the entity (manage the real one in a migration):

@Entity
@Table(name = "orders", indexes = @Index(
        name = "idx_orders_customer_created",
        columnList = "customer_id, created_at"))
class Order { /* id, customerId, totalCents, createdAt ... */ }

interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findTop20ByCustomerIdOrderByCreatedAtDesc(long customerId);
}
Enter fullscreen mode Exit fullscreen mode

Round 4: When the database ignores your index

Interviewer: You added the index and the planner still scans the table. Why?

You: Because sometimes the scan really is cheaper. An index finds matching rows fast, but each match then needs its table page, and those reads are random. PostgreSQL's default cost model charges 1 for a sequential page and 4 for a random one.

On a 10 million row table (100,000 pages): a query matching 631 rows costs about 2,500 via the index versus 100,000 for a full scan, so the index wins easily. But the break-even comes at roughly 0.3% of the table, about 29,000 rows. Past that, reading everything in order is cheaper than jumping around.

The index-or-scan calculator on Designbench
Index or scan on Designbench: 10 million rows, and the point where reading the whole table becomes cheaper.

Two things move the break-even a long way:

  • Clustered order: if the table is physically sorted by that column, matches sit next to each other and the reads become sequential.
  • Covering index: if the index holds every column the query needs, the database never touches the table. In PostgreSQL, add them with INCLUDE (total_cents).

Round 5: What indexes cost

Interviewer: Why not index every column?

You: Because every index is another B+tree to update. With 3 indexes on the orders table, each new order is 4 tree inserts: the table plus 3 indexes. Updates rewrite the indexes whose columns changed, and deletes touch all of them. Indexes also take disk and memory, and an index the planner never uses is pure cost.

So I start from the hot queries, list each WHERE and ORDER BY, give each an index or a reason it doesn't need one, and let one composite serve several queries where I can.

Say it in the interview

"I'd add a composite index on (customer_id, created_at DESC): equality column first, then the sort column, so the database seeks to the customer and reads 20 entries in order with no sort. A B+tree over a billion rows is only 4 levels deep, so that's a handful of page reads. For hot reads I'd make it covering. I'd check the plan with EXPLAIN, remember the planner prefers a scan once a query matches more than a few tenths of a percent of the table, and keep the index count low because every index slows writes."

Common mistakes

  • Indexing each column separately instead of one composite in the right order.
  • Putting a range column before an equality column.
  • Expecting an index to help a query that skips the leading column.
  • Surprise when the planner chooses a full scan for a query that matches a big share of rows.
  • Adding indexes without counting the write cost.
  • Building an index on a busy production table without a non-locking option.

Practise it

Grow the table, search the B+tree, test the composite rules and find the break-even yourself in the indexes lesson on Designbench. Related: SQL vs NoSQL, Sharding and Back-of-the-envelope math.

Top comments (0)