0Pricing
SQL Interview Prep · Lesson

B-Tree Indexes and How They Help

What an index actually stores and the operations it accelerates.

B-Tree Indexes and How They Help is a free SQL Interview Prep lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the SQL Interview Prep learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Interviewers Ask About Indexes

When an interviewer says 'this query is slow, what do you do?', the answer they are listening for almost always involves an index. Indexes are the single biggest lever on read performance, so they separate candidates who memorized syntax from those who understand how a database actually finds rows.

In this lesson you will build a precise mental model of the B-Tree index: what it stores, which operations it speeds up, and how to talk about it the way a senior engineer would.

The Problem an Index Solves

Without an index, finding rows that match a condition forces the database to read every row in the table. This is a sequential scan (or full table scan). On a million-row table, that means a million row checks even if only one row matches.

An index is a separate, sorted data structure that lets the engine jump straight to matching rows, the same way a book index lets you find a topic without reading every page.

-- No index: the engine reads ALL rows to find this one
SELECT * FROM users WHERE email = 'ada@example.com';

What a B-Tree Actually Stores

The default index in PostgreSQL, MySQL, SQL Server and most engines is a B-Tree (balanced tree). It stores the indexed column values in sorted order, organized into a shallow tree of pages.

  • Each leaf node holds index keys plus a pointer to the actual table row.
  • The tree stays balanced, so any lookup touches only a few pages, regardless of table size.

A lookup walks from the root down to a leaf in roughly log(N) steps instead of scanning all N rows.

Creating Your First Index

You create a B-Tree index with CREATE INDEX. Name it clearly so a reviewer knows the table and columns at a glance.

Once this index exists, a query filtering on email can use it to find the matching row in a handful of page reads instead of a full scan.

CREATE INDEX idx_users_email ON users (email);

-- Now this lookup uses the index instead of scanning
SELECT * FROM users WHERE email = 'ada@example.com';

Operations a B-Tree Accelerates

Because a B-Tree keeps values sorted, it speeds up far more than exact matches. Interviewers love when you list these precisely:

  • Equality: WHERE email = ?
  • Range: WHERE age > 30, BETWEEN, <, >=
  • Prefix matching: WHERE name LIKE 'Ada%' (but NOT '%da')
  • ORDER BY on the indexed column, avoiding a sort
  • MIN/MAX, since they sit at the ends of the sorted structure

Worked Example: Range Query

Consider an orders table with millions of rows. A reporting query asks for recent orders. With an index on created_at, the engine seeks to the start of the range in the sorted index and walks forward only as far as needed.

The index turns a full-table scan into a bounded range scan, reading just the qualifying slice.

CREATE INDEX idx_orders_created_at ON orders (created_at);

SELECT order_id, total
FROM orders
WHERE created_at >= '2026-01-01'
  AND created_at <  '2026-02-01';

Indexes Help Sorting Too

A frequently missed point: because the index is already sorted, the engine can return rows in index order and skip a separate sort step. This matters for ORDER BY and especially for top-N pagination.

If you sort by a column that has a matching index, the optimizer can read the index in order and stop early once it has enough rows.

-- Index on created_at lets this avoid a sort and stop after 10 rows
SELECT order_id, total
FROM orders
ORDER BY created_at DESC
LIMIT 10;

The Hidden Cost: the Heap Fetch

A normal B-Tree index stores only the indexed column plus a row pointer. So after finding matching entries, the engine still has to go to the table (the heap) to read the other columns you selected.

That second hop is the heap fetch. It is cheap for a few rows but expensive when a query matches many rows, which is one reason a low-selectivity index is sometimes ignored. (You will see covering indexes solve this later.)

Confirming the Index Is Used

Never claim an index is used, prove it with EXPLAIN. In an interview, narrating the plan shows real understanding.

  • Seq Scan means the index was NOT used.
  • Index Scan or Index Seek means it was.

If you added an index but still see a sequential scan, the planner judged the scan cheaper, often because the query matches too large a fraction of the table.

EXPLAIN
SELECT * FROM users WHERE email = 'ada@example.com';
-- Look for: Index Scan using idx_users_email

Primary Keys Are Already Indexed

A common interview gotcha: declaring a PRIMARY KEY or UNIQUE constraint automatically creates a supporting B-Tree index. You do not, and should not, add a second index on the same column.

This is why joins and lookups on primary keys are already fast, and why the question 'should I index the id column?' is usually a trap, it is already done for you.

-- This already builds a unique B-Tree index on (id)
CREATE TABLE users (
  id    BIGINT PRIMARY KEY,
  email TEXT UNIQUE
);

How to Phrase It in the Interview

Tie it together with a clean one-liner an interviewer can nod along to:

'A B-Tree index is a sorted, balanced structure that lets the engine find rows in log(N) page reads instead of scanning the whole table. It accelerates equality, range, prefix, and ORDER BY operations on the indexed columns, but each match still costs a heap fetch for non-indexed columns.'

Then back it with EXPLAIN. That combination of model plus evidence is what scores points.

Quick Check

Test your mental model of what a B-Tree index accelerates.

Recap: B-Tree Indexes

Key takeaways to carry into the next lesson:

  • A B-Tree stores indexed values sorted in a balanced tree, giving log(N) lookups.
  • It accelerates equality, range, prefix (leading) LIKE, ORDER BY, and MIN/MAX.
  • Each match still needs a heap fetch for columns not in the index.
  • Wrapping a column in a function or using a leading wildcard disables the index.
  • Always verify with EXPLAIN; PRIMARY KEY and UNIQUE constraints index automatically.

Next: how to order columns when one index covers several at once.

Frequently asked questions

Is the “B-Tree Indexes and How They Help” lesson free?

Yes — the full text of “B-Tree Indexes and How They Help” is free to read here on the web, and the SQL Interview Prep course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the SQL Interview Prep course, upgrade to CoddyKit PRO.

What will I learn in “B-Tree Indexes and How They Help”?

What an index actually stores and the operations it accelerates. You practise SQL Interview Prep with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start SQL Interview Prep?

No prior experience is required. SQL Interview Prep on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “B-Tree Indexes and How They Help” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this SQL Interview Prep lesson?

Yes. Every SQL Interview Prep lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. B-Tree Indexes and How They Help
  2. Composite Index Column Order
  3. Covering Indexes and Index-Only Scans
  4. When Indexes Hurt: Writes and Selectivity
← Back to SQL Interview Prep