Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 123/ 160
07. Indexing, Query Optimization & Performance Tuning

B-Tree Indexes (Single-Column vs Composite / Multi-Column Indexes)

Create single-column and composite B-Tree indexes for common predicates.

BeginnerB-Tree · Composite Index3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

An index sorts some columns so the database can jump to matching rows; the order of columns decides which questions it can answer.

Think of it like…

A phone book sorted by surname, then first name: it's perfect for "Sharma, Priya" and good for "all Sharmas", but useless for "everyone called Priya". Two separate lists, one by surname and one by first name, would need to be cross-checked by hand.

Where you’ve seen it

An orders API runs SELECT … FROM orders WHERE customer_id = $1 AND status = 'shipped' ORDER BY created_at DESC LIMIT 20. Separate indexes on customer_id and status make PostgreSQL combine bitmaps and then sort, taking 35 ms. A composite index on (customer_id, status, created_at DESC) jumps straight to the 20 rows in order and takes 0.2 ms, and the two single-column indexes can be dropped.

Words you’ll hear

Composite index
One B-tree sorted by several columns in a fixed order.
Equality, sort, range (ESR)
Column order rule: = columns, then ORDER BY column, then range columns.
BitmapAnd
PostgreSQL combining two single-column indexes; works, but rarely as well as one composite.
Redundant index
An index whose columns are a prefix of another, such as (a) next to (a, b).

Visual diagram

Loading interactive diagram

Theory & example queries

Single-column vs composite

A single-column index is enough when one column is selective on its own, such as email or order_id. When queries combine conditions, PostgreSQL can merge single-column indexes with a BitmapAnd, and MySQL with an index merge, but that reads both indexes in full for the matching values and can't return rows in order. A composite index on the combination narrows to the exact rows in one descent and can satisfy ORDER BY and LIMIT directly.

Order the columns by how they're used: equality columns first (their order among themselves matters little for that query, so put the one shared by more queries first), then the column you ORDER BY, then columns with range conditions. A range on an early column stops the index from using the columns after it for seeking, which is why (created_at, customer_id) is a poor index for customer_id = ? AND created_at > ?.

Range after equalityQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE INDEX orders_cust_created_idx ON orders (customer_id, created_at);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/1
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
CREATE INDEX

Note: Representative PostgreSQL status; index build time and lock duration depend on table size and build options.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

serves WHERE customer_id = 42 AND created_at >= '2026-11-01' by seeking to customer 42's November entries; the reverse order would scan every November order.

Key takeaway: One composite in ESR order beats several single-column indexes for combined filters.

Sort direction, NULLs and index hygiene

A B-tree can be read forwards or backwards, so (customer_id, created_at) serves both ASC and DESC on created_at. Mixed directions such as ORDER BY priority DESC, created_at ASC need an index declared the same way: (priority DESC, created_at ASC). PostgreSQL indexes NULLs, so IS NULL can use an index, and NULLS FIRST or LAST can be declared to match an ORDER BY.

Every index slows inserts and updates and competes for cache. Drop indexes that are prefixes of others ((a) when (a, b) exists), and find unused ones with SELECT indexrelname, idx_scan FROM pg_stat_user_indexes WHERE idx_scan = 0, after checking replicas and rare monthly jobs. Build new indexes on busy tables with CREATE INDEX CONCURRENTLY.

Finding unused indexes and their sizeQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  relname AS table_name,3  indexrelname AS index_name,4  idx_scan,5  pg_size_pretty(pg_relation_size(indexrelid)) AS size6FROM7  pg_stat_user_indexes8WHERE9  idx_scan = 010ORDER BY11  pg_relation_size(indexrelid) DESC;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
table_nameindex_nameidx_scansize
eventsevents_payload_gin0824 MB
ordersorders_old_status_idx096 MB
sessionssessions_device_idx014 MB

Note: Illustrative PostgreSQL statistics; recent restarts and stats resets can make low idx_scan values misleading.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Match mixed sort directions; drop redundant and unused indexes.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Query

Collect the query's conditions

List equality filters, the ORDER BY, range filters and the LIMIT for the queries that matter most.

SQL at this stepReadable preview
1= customer_id, = status ·2ORDER BY created_at DESC ·3LIMIT 20
What to watch at this step
Focus
hot queries
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A single-column B-tree index serves filters and sorts on that column; a composite index on (a, b, c) serves queries that filter on a, on a and b, or on a, b and c, and can return rows already sorted. The rule for column order is equality, then sort, then range: columns compared with = first, the ORDER BY column next, range conditions last. One well-designed composite index usually beats several single-column ones.

Why it matters: Most production performance problems are fixed by the right B-tree index, and most index mistakes are about choosing between composite and single-column indexes or getting the column order wrong. Too many indexes slow every write and waste memory. Interviewers often give a query and ask exactly which index you'd create.

When to reach for it

  • Composite indexes for API queries with filters plus ORDER BY … LIMIT
  • Single-column indexes for unique lookups like email
  • Regular reviews of unused and duplicate indexes

When to avoid or be careful

  • Putting range columns before equality columns
  • One index per column "just in case"
  • Keeping (a) when (a, b) already exists

Single-column indexes vs one composite index

Several single-column indexes
Best for: Columns filtered separately in different queries

Strengths: Flexible; each serves its own column.

Watch out: Combined filters need bitmap merging; can't provide sort order for both.

One composite index
Best for: Queries that filter and sort on the same columns together

Strengths: Exact rows in one descent; supports ORDER BY + LIMIT.

Watch out: Only helps queries using its leading columns.

Composite + INCLUDE columns
Best for: Hot queries that can be answered from the index alone

Strengths: Index-only scans.

Watch out: Larger index; more write cost.

Interview signals & numbers to know

When this topic comes up

  • “Which index would you add for this query?”
  • “We have 14 indexes on this table and writes are slow”
  • “Single or composite index?”
  • ORDER BY + LIMIT queries
  • Index column order

Benchmarks & rules of thumb

E → S → R -
column order: equality, sort, range
0 -
idx_scan of an unused index
1 -
descent for a well-designed composite lookup

Common mistakes & follow-ups

Common interview mistakes

  • Indexing (created_at, customer_id) for WHERE customer_id = ? AND created_at > ?, so every recent order is scanned.
  • Adding separate indexes on customer_id and status and expecting the same speed as a composite.
  • Dropping an index with idx_scan = 0 on the primary that a read replica's reports depend on.

Likely interviewer follow-ups

  • What index would you create for WHERE a = ? AND b > ? ORDER BY c?
  • When are two single-column indexes as good as a composite one?
  • How do you find indexes you can safely remove?
Interview tip: Map each part of the query to an index position out loud: equality, sort, range. Interviewers want to hear the reasoning, not just a column list.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply B-Tree Indexes (Single-Column vs Composite / Multi-Column Indexes) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
How Indexes Work & The Read vs Write Trade-off
Next topic
Leftmost Prefix Rule & Column Ordering in Composite Indexes