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 124/ 160
07. Indexing, Query Optimization & Performance Tuning

Leftmost Prefix Rule & Column Ordering in Composite Indexes

Order composite index columns so the leftmost prefix matches your filters.

IntermediateLeftmost Prefix · Column Order3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A multi-column index is sorted by its first column first, so it only helps when you filter on that first column (and then the next ones, in order).

Think of it like…

A phone book sorted by last name, then first name. Finding "Sharma, Ravi" is fast, and so is finding every Sharma. Finding everyone called Ravi means reading the whole book.

Where you’ve seen it

An index on orders(customer_id, created_at) serves WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10 perfectly: it jumps to customer 42 and reads their orders already sorted. WHERE created_at > now() - interval '1 day' on its own can't seek into it.

Words you’ll hear

Composite index
One index on several columns, sorted column by column.
Leftmost prefix
The first column, or the first N columns in order.
Equality vs range
Columns compared with = can be followed by more seekable columns; after a range (<, >, BETWEEN) the rest can only filter.
Skip scan
A feature in some engines that can use a non-leading column when the leading one has few values.

Visual diagram

Loading interactive diagram

Theory & example queries

Why only the leftmost prefix works

The index entries are ordered by a, and only within equal values of a are they ordered by b. To find rows where b = 5, the database would have to look inside every a group, which is a full index scan rather than a seek.

That's why INDEX (a, b) also serves queries filtering only on a, making a separate INDEX (a) redundant. It also serves WHERE a = ? ORDER BY b without a sort, since the matching entries are already in b order.

One index, several queriesQuery 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 idx_orders_cust_date 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.
Representative command status
CREATE INDEX

Note: The command creates the composite index if permitted and if the name is unused; actual build time depends on table size and concurrent load.

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

serves WHERE customer_id = ?, WHERE customer_id = ? AND created_at >= ? and WHERE customer_id = ? ORDER BY created_at DESC LIMIT 10.

Key takeaway: A composite index is searchable from its first column, left to right.

Choosing the column order

Put columns compared with equality first, then the one range column, then columns used only for sorting. Once a column is used as a range (created_at > ?), the columns after it in the index can only filter rows, not narrow the search.

The common advice "most selective column first" matters less than the equality-then-range rule, and the right order also depends on which queries you need to serve. Some engines (Oracle, MySQL 8.0.13+, PostgreSQL 18+) have a skip scan that can sometimes use a non-leading column when the leading one has few distinct values, but don't design your indexes around it.

Equality before range

For WHERE status = 'paid' AND created_at >= '2026-01-01', index (status, created_at) seeks straight to paid orders from 2026. Index (created_at, status) has to scan every order since January and check status on each.

Key takeaway: Equality columns first, range column last.
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 1Workload

List the queries to serve

Write down the WHERE and ORDER BY of the important queries on the table. An index is designed for queries, not columns.

SQL at this step
1WHERE2  customer_id = ?3ORDER BY4  created_at DESC
What to watch at this step
Start from
real queries
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A composite index on (a, b, c) is sorted by a, then by b within each a, then by c. So it can be searched efficiently only through a leftmost prefix of its columns: filters on a, on a and b, or on a, b and c. A filter on b or c alone can't use it to jump to the right rows.

Why it matters: Column order is the most common reason a composite index "isn't being used". Getting it right lets one index serve several queries; getting it wrong means slow queries and a pile of redundant indexes. It's a favourite interview follow-up after "how do indexes work?".

When to reach for it

  • Queries that filter on one column and sort or range on another
  • Multi-tenant tables where every query filters on tenant_id first
  • Replacing several overlapping single-column indexes

When to avoid or be careful

  • Putting the range column before equality columns
  • Keeping INDEX (a) when INDEX (a, b) exists
  • Expecting an index on (a, b) to help queries that filter only on b

One composite index vs separate indexes

Composite INDEX (a, b)
Best for: Queries that filter on a, or on a and b together

Strengths: One seek straight to the matching rows, and sorted by b within a.

Watch out: Useless for seeking on b alone.

Separate INDEX (a) and INDEX (b)
Best for: Workloads that filter on a or b independently

Strengths: Each column can be searched on its own.

Watch out: Combining them (bitmap AND) is usually slower than one good composite index, and both cost writes.

Covering INDEX (a, b) INCLUDE (c)
Best for: Hot queries that also read c

Strengths: Index-only scan: no table access needed.

Watch out: Larger index, more write overhead.

Interview signals & numbers to know

When this topic comes up

  • “Why isn't my composite index being used?”
  • “In what order should index columns go?”
  • Filtering on one column and sorting by another
  • tenant_id on every query
  • Redundant indexes

Benchmarks & rules of thumb

(a, b, c) -
seekable via a; a, b; or a, b, c
1 -
range column worth putting in the seek part
(a) -
redundant if (a, b) exists

Common mistakes & follow-ups

Common interview mistakes

  • Creating INDEX (created_at, customer_id) for queries that filter on customer_id = ? and sort by date.
  • Assuming any query mentioning an indexed column can use the index, regardless of position.
  • Adding a separate index for every query instead of designing one composite index that serves several.

Likely interviewer follow-ups

  • An index exists on (a, b). Which of these can use it: WHERE a = 1, WHERE b = 2, WHERE a = 1 ORDER BY b?
  • Why put equality columns before range columns?
  • When would two single-column indexes be better than one composite index?
Interview tip: Use the phone book analogy, then state the rule: equality columns first, range last, and the index only helps from the leftmost column. Interviewers usually follow with a which-query-can-use-it question, so practise those.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Leftmost Prefix Rule & Column Ordering in Composite Indexes with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
B-Tree Indexes (Single-Column vs Composite / Multi-Column Indexes)
Next topic
Covering Indexes (INCLUDE Clause) & Index-Only Scans