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

Covering Indexes (INCLUDE Clause) & Index-Only Scans

Satisfy queries from the index alone using INCLUDE and covering designs.

IntermediateCovering Index · INCLUDE3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Put the columns your query needs right inside the index, so the database never has to go back to the table.

Think of it like…

A phone book that lists name, number and address: if you only need a number, the book answers you directly. If it only listed names with page references, you'd have to go to another book for every person.

Where you’ve seen it

An order-history API runs SELECT status, amount FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20 thousands of times a minute. An index on (customer_id, created_at DESC) INCLUDE (status, amount) lets it return all 20 rows from the index.

Words you’ll hear

Key columns
Columns the index is sorted by; used for searching and ordering.
INCLUDE columns
Extra columns stored only in leaf entries; carried along, not searchable.
Index-only scan
A plan that reads only the index, not the table (heap).
Visibility map
PostgreSQL's record of all-visible pages; index-only scans depend on it being up to date.

Visual diagram

Loading interactive diagram

Theory & example queries

Key columns vs INCLUDE columns

Columns in the index key are sorted and can be used to search, filter ranges and avoid sorts. Columns in INCLUDE are only stored alongside each entry, so they can be returned but not searched efficiently. Put filter and sort columns in the key, and columns that are only selected in INCLUDE.

In MySQL's InnoDB, every secondary index already stores the primary key, so a query needing only indexed columns plus the primary key is covered automatically. MySQL has no INCLUDE clause, so extra columns have to be added to the key itself.

Covering a hot API queryQuery 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.sqlReadable preview
1CREATE INDEX idx_orders_customer_recent ON orders (customer_id,2  created_at DESC) INCLUDE (status,3  amount);
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/3
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
CREATE INDEX

Note: Representative PostgreSQL status; build time and the exact command text used by another dialect can differ.

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

Key takeaway: Search and sort columns go in the key; selected-only columns go in INCLUDE.

When index-only scans actually happen

PostgreSQL also has to know each row is visible to your transaction. It checks the visibility map, and only pages marked all-visible can skip the table. EXPLAIN ANALYZE shows Heap Fetches: a high number means it still visited the table, usually because the table changes a lot or VACUUM hasn't run recently.

Covering indexes are for a few critical queries, not a general strategy. Each one is larger than a plain index and adds write cost, and adding a column to the query (or SELECT *) silently drops it back to a normal index scan.

Checking it in the planQuery 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
1EXPLAIN (2  ANALYZE3)4SELECT5  status,6  amount7FROM8  orders9WHERE10  customer_id = 4211ORDER BY12  created_at DESC13LIMIT14  20;
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/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
Limit (actual rows=20 loops=1) -> Index Only Scan using idx_orders_customer_recent on orders (actual rows=20 loops=1) Index Cond: (customer_id = 42) Heap Fetches: 0 Planning Time: varies Execution Time: varies

Note: Representative PostgreSQL plan shape only; costs, timing, rows and heap fetches vary with data, visibility maps, cache state and planner statistics.

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

should show Index Only Scan using idx_orders_customer_recent with Heap Fetches: 0 or close to it.

Key takeaway: Verify Index Only Scan and low Heap Fetches; keep VACUUM healthy.

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

Pick a hot, narrow query

Choose a frequently run query that selects a few columns, found with pg_stat_statements or slow query logs.

SQL at this stepReadable preview
1SELECT status,2  amount …3WHERE customer_id = ?
What to watch at this step
Good fit
few columns, many calls
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A covering index contains every column a query needs, so the database can answer it from the index alone with an index-only scan, without visiting the table. In PostgreSQL 11+ and SQL Server you add the extra columns with INCLUDE: CREATE INDEX ON orders (customer_id) INCLUDE (status, amount).

Why it matters: For hot queries that return many rows, fetching each row from the table can cost more than finding it in the index. Covering those queries can cut I/O dramatically. It's also a common follow-up in indexing interviews: "how would you make this even faster without changing the query?"

When to reach for it

  • High-traffic API queries that read a few columns
  • Dashboards that repeatedly aggregate a few columns by a key
  • Pagination queries that select a small, fixed column list

When to avoid or be careful

  • Covering indexes for queries that select many or all columns
  • Adding INCLUDE indexes everywhere "just in case"
  • Expecting index-only scans on heavily updated tables without healthy VACUUM

Plain index vs wider key vs INCLUDE

Plain index on the filter column
Best for: Most queries

Strengths: Small and cheap to maintain.

Watch out: Each matching row needs a table lookup.

Extra columns added to the key
Best for: MySQL, or when the extra columns are also filtered or sorted on

Strengths: Covers the query and can be searched on.

Watch out: Larger keys throughout the tree; column order matters.

INCLUDE columns
Best for: Covering hot queries in PostgreSQL 11+ and SQL Server

Strengths: Covers the query without affecting the sort order or upper index levels.

Watch out: Larger index and more write work.

Interview signals & numbers to know

When this topic comes up

  • “How can we make this query faster without changing it?”
  • “What's an index-only scan?”
  • Index Scan with many heap fetches
  • Hot read path
  • INCLUDE clause

Benchmarks & rules of thumb

PostgreSQL 11 -
INCLUDE introduced
Heap Fetches: 0 -
ideal index-only scan
1 table lookup -
per row saved

Common mistakes & follow-ups

Common interview mistakes

  • Adding a column to the SELECT list later and silently losing the index-only scan.
  • Putting INCLUDE columns first in the index key, which wrecks its usefulness for searching.
  • Expecting an index-only scan on a constantly updated table with an out-of-date visibility map.

Likely interviewer follow-ups

  • What's the difference between adding a column to the index key and adding it with INCLUDE?
  • Why might PostgreSQL still read the table during an index-only scan?
  • When is a covering index not worth it?
Interview tip: Explain the extra table lookup first, then show INCLUDE removing it, and mention Heap Fetches and VACUUM. That PostgreSQL detail shows real hands-on tuning.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Covering Indexes (INCLUDE Clause) & Index-Only Scans with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Leftmost Prefix Rule & Column Ordering in Composite Indexes
Next topic
Partial Indexes (Filtered Indexes) & Expression / Functional Indexes