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

Index Scan vs Index-Only Scan vs Bitmap Scan vs Sequential Scan

Read EXPLAIN node types and know when seq scans are actually fine.

IntermediateIndex Scan · Bitmap Scan3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

The database can read the whole table, jump to rows one by one using an index, answer straight from the index, or collect a list of rows first and read them in order.

Think of it like…

Finding recipes in a cookbook: read every page (Seq Scan); use the index and flip to each page one by one (Index Scan); get the answer from the index itself because it lists the cooking time (Index Only Scan); or note all the page numbers first, sort them, and flip through in order (Bitmap Scan).

Where you’ve seen it

On a 10-million-row orders table: WHERE id = 42 uses an Index Scan (one row); WHERE status = 'pending' matching 50,000 rows uses a Bitmap Heap Scan; WHERE created_at > '2020-01-01' matching 95% of rows uses a Seq Scan, which is correct, because reading everything in order is cheapest.

Words you’ll hear

Seq Scan
Reads all table pages sequentially; best when many rows match or the table is small.
Index Scan
Index lookup, then a random table read per row; best for few rows.
Bitmap Heap Scan
Gathers matching row locations, sorts them by page, then reads pages once each.
Index Only Scan
Reads only the index when it contains every needed column.

Visual diagram

Loading interactive diagram

Theory & example queries

How each scan reads data

A Seq Scan reads the table front to back, which is efficient for disks and caches but touches every row. An Index Scan uses the index to find matching entries in order and fetches each row from the table, one random page read per row. That's ideal for a handful of rows, and it also returns rows in index order, which can avoid a sort.

A Bitmap Index Scan collects the locations of all matching rows into a bitmap (possibly combining several indexes with BitmapAnd or BitmapOr), and a Bitmap Heap Scan then visits each table page once, in physical order. For thousands of matches that's much cheaper than random fetches. If the bitmap gets too large for memory it becomes lossy, which is why you may see a Recheck Cond line.

Two indexes combinedQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1EXPLAIN2SELECT3  *4FROM5  orders6WHERE7  status = 'pending'8  AND region = 'south';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative plan fragment
Bitmap Heap Scan on orders Recheck Cond: ((status = 'pending') AND (region = 'south')) -> BitmapAnd -> Bitmap Index Scan on idx_orders_status -> Bitmap Index Scan on idx_orders_region

Note: The planner can instead choose one index, a sequential scan or another plan based on PostgreSQL statistics, selectivity and costs.

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

can show BitmapAnd over Bitmap Index Scan on idx_orders_status and Bitmap Index Scan on idx_orders_region, then a Bitmap Heap Scan.

Key takeaway: Few rows: Index Scan. Thousands: Bitmap. Most of the table: Seq Scan.

When a Seq Scan is right, and when it isn't

If a query returns a large fraction of a table, or the table fits in a few pages, a Seq Scan beats any index plan, and the planner is right to choose it. It's a problem only when few rows match and the planner still scans: usually a missing index, a non-SARGable condition (a function on the column), or statistics that overestimate the matches.

The planner weighs random reads against sequential ones with random_page_cost (default 4, tuned for spinning disks). On SSDs, setting it to about 1.1 stops the planner undervaluing index plans. MySQL shows the same ideas differently in EXPLAIN: type = ALL for a full scan, range or ref for index access, and "Using index" for a covering index.

Checking the estimate behind a Seq ScanQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1EXPLAIN2ANALYZE3SELECT4  *5FROM6  orders7WHERE8  customer_id = 42;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative problematic plan fragment
Seq Scan on orders (cost=0.00..52000.00 rows=500000) Filter: (customer_id = 42) Rows Removed by Filter: 499988 (actual time=... rows=12 loops=1)

Note: Costs and timings are deliberately omitted as variable. A large estimate/actual mismatch is diagnostic; refresh statistics and then consider an index only if the plan remains unsuitable.

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

If it shows Seq Scan … (rows=500000) (actual rows=12), the estimate is wrong or an index is missing on customer_id.

Key takeaway: Judge a scan by how many rows it returns, not by its name.

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 1Plan

Run EXPLAIN ANALYZE

Find the scan node for each table and note its type, estimated rows and actual rows.

SQL at this stepReadable preview
1Seq Scan on orders (rows=… actual rows=…)
What to watch at this step
Note
type + rows
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

EXPLAIN shows how PostgreSQL reads a table. A Seq Scan reads every page in order. An Index Scan walks the index and fetches each matching row from the table. An Index Only Scan answers from the index alone. A Bitmap Index Scan + Bitmap Heap Scan first collects all matching row locations from one or more indexes, then reads the table pages in physical order. Each wins at a different share of matching rows.

Why it matters: "Why isn't it using my index?" usually has a good answer: for the number of rows involved, another scan type is cheaper. Reading scan nodes lets you tell a genuinely bad plan from a sensible one, which is a core skill in performance interviews.

When to reach for it

  • Reading EXPLAIN output during query tuning
  • Explaining why an index wasn't used
  • Deciding whether an index is worth adding

When to avoid or be careful

  • Forcing index use with enable_seqscan = off in production
  • Treating every Seq Scan as a problem
  • Leaving random_page_cost at the spinning-disk default on SSD storage

Scan types side by side

Index Scan / Index Only Scan
Best for: Selective conditions returning few rows

Strengths: Touches only matching rows; can return them already sorted.

Watch out: Random reads get expensive as matches grow.

Bitmap Index + Bitmap Heap Scan
Best for: Moderate numbers of matches, or several indexes combined

Strengths: Reads each table page once, in order.

Watch out: Doesn't return rows in index order; can need a recheck.

Seq Scan
Best for: Small tables or queries returning a large share of rows

Strengths: Fast sequential I/O, no index overhead.

Watch out: Reads everything, so it's terrible for selective queries on big tables.

Interview signals & numbers to know

When this topic comes up

  • “Why isn't my index being used?”
  • Bitmap Heap Scan in EXPLAIN
  • “What's the difference between an Index Scan and an Index Only Scan?”
  • Slow query with a Seq Scan
  • Query planner choices

Benchmarks & rules of thumb

4 -
default random_page_cost
~1.1 -
typical random_page_cost on SSDs
1 -
visit per table page in a bitmap heap scan

Common mistakes & follow-ups

Common interview mistakes

  • Adding indexes to make a query that returns 80% of the table "use an index".
  • Missing that a Seq Scan comes from WHERE LOWER(email) = … rather than from a missing index.
  • Assuming a Bitmap Heap Scan's output is sorted the way the index is.

Likely interviewer follow-ups

  • When would PostgreSQL choose a Bitmap Heap Scan over an Index Scan?
  • Why might a Seq Scan be faster than an index scan?
  • What's the MySQL EXPLAIN equivalent of a sequential scan?
Interview tip: Explain the scans as a spectrum by how many rows match, then say "a Seq Scan is only a problem when few rows match". That reframing is what interviewers want to hear.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Index Scan vs Index-Only Scan vs Bitmap Scan vs Sequential Scan with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Specialized Indexes (Hash, GIN, GiST, BRIN for Time-Series)
Next topic
Reading & Interpreting EXPLAIN and EXPLAIN ANALYZE Output