Index Design

Updated · 11 min read
hardPostgreSQL 18sqlindex-designb-treecomposite-indexcovering-indexpartial-indexinterview

Index design in SQL is choosing which columns to index, in what order, and with what extras, so that the queries you actually run can find their rows by reading as few pages as possible. Indexes showed that an index can turn a full scan into a quick lookup. This lesson is about choosing the right index: how a B-tree finds a value, why the order of columns in a composite index decides which queries it helps, how a covering index skips the table entirely, and when partial and expression indexes are the better choice. Every comparison uses real plans and buffer counts.

In One Minute

  • A B-tree index keeps values sorted in a shallow tree, so a lookup reads only a few pages.
  • A composite index (a, b) helps queries on a, or on a and b, but not on b alone.
  • A covering index (INCLUDE (col)) holds extra columns, so the query is answered by an Index Only Scan.
  • A partial index (WHERE ...) indexes only the rows you query, and is smaller.
  • An expression index (ON (lower(email))) helps queries that use that expression.

How an Index Lookup Works

A B-tree stores the indexed values in sorted order across pages, with a small tree of pages on top to find the right one. To find student_id = 1234, the database starts at the root page, follows the pointer for the range containing 1234, and reaches a leaf page listing the matching row locations. Even for millions of rows, that's typically 3 or 4 pages. Then it fetches the rows from the table.

Root page, then the branch for 1234, then the leaf listing its row locations: a few pages instead of the whole table

The examples use the generated big_payments table from How a Query Runs: 20,000 payments for 5,000 students over two years, 128 pages in all.

Column Order in Composite Indexes

A composite index is sorted by its first column, then by the second within each first value, like a phone book sorted by last name, then first name. An index on (student_id, paid_on) serves a query on both columns:

SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
CREATE INDEX big_payments_student_paid_idx ON big_payments (student_id, paid_on);
ANALYZE big_payments;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT count(*) FROM big_payments WHERE paid_on = '2025-06-01';
Output
CREATE TABLE
 
INSERT 0 20000
 
CREATE INDEX
 
ANALYZE
 
                         QUERY PLAN
------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=128
   ->  Seq Scan on big_payments (actual rows=27.00 loops=1)
         Filter: (paid_on = '2025-06-01'::date)
         Rows Removed by Filter: 19973
         Buffers: shared hit=128
 Planning:
   Buffers: shared hit=23 read=2
(8 rows)

Explanation: This query filters on paid_on alone, the second column. Its values are scattered through the index, one small group per student, so the planner can't use it and scans all 128 pages. Reversing the order fixes this query:

SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
CREATE INDEX big_payments_paid_student_idx ON big_payments (paid_on, student_id);
ANALYZE big_payments;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT count(*) FROM big_payments WHERE paid_on = '2025-06-01';
Output
CREATE TABLE
 
INSERT 0 20000
 
CREATE INDEX
 
ANALYZE
 
                                         QUERY PLAN
--------------------------------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=27 read=3
   ->  Bitmap Heap Scan on big_payments (actual rows=27.00 loops=1)
         Recheck Cond: (paid_on = '2025-06-01'::date)
         Heap Blocks: exact=27
         Buffers: shared hit=27 read=3
         ->  Bitmap Index Scan on big_payments_paid_student_idx (actual rows=27.00 loops=1)
               Index Cond: (paid_on = '2025-06-01'::date)
               Index Searches: 1
               Buffers: shared read=3
 Planning:
   Buffers: shared hit=20 read=2
(12 rows)

Explanation: With paid_on first, all of one day's entries are together, and the index finds the 27 payments by reading 3 index pages and the 27 table pages that hold them: 30 pages instead of 128.

IndexWHERE student_id = ?WHERE student_id = ? AND paid_on = ?WHERE paid_on = ?
(student_id, paid_on)YesYesNo
(paid_on, student_id)NoYesYes

Covering Indexes: INCLUDE

A covering index contains every column a query needs, so the query never visits the table. INCLUDE adds columns to the index's leaf pages without making them part of the sort order:

SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
CREATE INDEX big_payments_student_cover_idx ON big_payments (student_id) INCLUDE (amount_usd);
VACUUM ANALYZE big_payments;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT sum(amount_usd) FROM big_payments WHERE student_id = 1234;
Output
CREATE TABLE
 
INSERT 0 20000
 
CREATE INDEX
 
VACUUM
 
                                              QUERY PLAN
-------------------------------------------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=1 read=2
   ->  Index Only Scan using big_payments_student_cover_idx on big_payments (actual rows=4.00 loops=1)
         Index Cond: (student_id = 1234)
         Heap Fetches: 0
         Index Searches: 1
         Buffers: shared hit=1 read=2
 Planning:
   Buffers: shared hit=27 read=3
(9 rows)

Explanation: Index Only Scan with Heap Fetches: 0: the amounts came straight from the index, 3 pages in all, with no table pages. Without INCLUDE (amount_usd), the same query reads the index and then 4 table pages. VACUUM matters here: an index-only scan skips the table only for pages the visibility map marks as all-visible.

Without INCLUDE: index, then table pages. With INCLUDE (amount_usd): the index alone answers the query

Partial and Expression Indexes

A partial index indexes only the rows matching a WHERE condition, so it's smaller and cheaper to maintain:

SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
CREATE INDEX big_payments_cash_paid_idx ON big_payments (paid_on) WHERE method = 'cash';
CREATE INDEX big_payments_paid_idx ON big_payments (paid_on);
ANALYZE big_payments;
 
SELECT pg_size_pretty(pg_relation_size('big_payments_cash_paid_idx')) AS partial_index,
       pg_size_pretty(pg_relation_size('big_payments_paid_idx')) AS full_index;
Output
CREATE TABLE
 
INSERT 0 20000
 
CREATE INDEX
 
CREATE INDEX
 
ANALYZE
 
 partial_index | full_index
---------------+------------
 80 kB         | 168 kB
(1 row)

Explanation: The partial index covers only cash payments, a third of the rows, and is about half the size. A query that includes method = 'cash' in its WHERE can use it. Partial indexes are ideal when queries focus on a small, fixed subset, such as WHERE status = 'active' or WHERE paid_on IS NULL.

An expression index indexes the result of an expression, for queries that filter on it. CREATE UNIQUE INDEX ON students (lower(email)), from Indexes, makes WHERE lower(email) = ... fast and case-insensitively unique.

Other Index Types and Databases

Index typeGood for
B-tree (default)=, ranges, ORDER BY, prefix LIKE 'abc%'
Hash= only
GINArrays, jsonb and full-text search (JSON in SQL, Full-Text Search)
GiST, SP-GiST, BRINGeometry and ranges; very large, naturally ordered tables

SQL Server has clustered indexes, which store the table itself in index order (one per table, usually the primary key), and nonclustered ones like PostgreSQL's. PostgreSQL tables aren't clustered; CLUSTER reorders a table once but doesn't keep it ordered. MySQL's InnoDB always clusters the table on its primary key (or, without one, on the first unique NOT NULL index or a hidden row id). Tabs showing each database's version are coming to this course.

Leftmost Column First

Common Mistakes

The wrong column order. An index on (student_id, paid_on) doesn't help WHERE paid_on = ....

One index per column. Several single-column indexes are rarely as good as one composite index matched to the query.

Expecting index-only scans without VACUUM. Recently changed pages still need table visits.

Indexing columns with few values for broad queries. If a query returns a large share of the table, a scan is cheaper anyway.

Interview Corner

Does column order matter in a composite index?

Yes. A B-tree composite index is sorted by its first column, then the second. It helps queries on the leading column or columns, not on a later column alone.

What is a covering index?

An index containing all the columns a query needs, often via INCLUDE, so the query can be answered by an index-only scan without reading the table.

What is a partial index?

An index with a WHERE clause that indexes only matching rows, making it smaller and faster for queries on that subset.

Practice

Challenge (module checkpoint): On the generated table, the report "how many payments on 2025-06-01?" reads all 128 pages. Add one index that makes it read at least ten times fewer pages, and show the new plan with buffers.

Show solution
SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
CREATE INDEX big_payments_paid_on_idx ON big_payments (paid_on) INCLUDE (payment_id);
VACUUM ANALYZE big_payments;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT count(*) FROM big_payments WHERE paid_on = '2025-06-01';
Output
CREATE TABLE
 
INSERT 0 20000
 
CREATE INDEX
 
VACUUM
 
                                            QUERY PLAN
--------------------------------------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=1 read=3
   ->  Index Only Scan using big_payments_paid_on_idx on big_payments (actual rows=27.00 loops=1)
         Index Cond: (paid_on = '2025-06-01'::date)
         Heap Fetches: 0
         Index Searches: 1
         Buffers: shared hit=1 read=3
 Planning:
   Buffers: shared hit=21 read=1
(9 rows)

An index on paid_on, plus VACUUM so the planner can trust the visibility map, lets PostgreSQL count the 27 payments from the index alone: 4 pages instead of 128, thirty-two times fewer. Compare the "before" plan in Reading EXPLAIN's practice. The Performance Lab in the last chapter has more queries to speed up the same way.

Quick check: Index design

3 questions
1Which query can use an index on (student_id, paid_on)?
2What does INCLUDE (amount_usd) add to an index?
3When is a partial index most useful?

Key Takeaways

You want toWrite
Filter on a then bCREATE INDEX ... ON t (a, b)
Answer from the indexCREATE INDEX ... ON t (a) INCLUDE (c)
Index a subsetCREATE INDEX ... ON t (a) WHERE status = 'active'
Index an expressionCREATE INDEX ... ON t (lower(email))

Was this tutorial helpful?

Lesson 81 of 115