SQL course · Module 9: Performance · Lesson 31 of 40
Quick answer: A SQL index is a separate structure, usually sorted, that points to rows in a table, so the database can find matching rows without reading the whole table. In PostgreSQL, CREATE INDEX name ON table (column); builds a B-tree index by default. A composite index covers several columns and works best when the query filters on the leftmost ones; a covering index adds extra columns with INCLUDE so the query can skip the table; a partial index stores only the rows that match a WHERE condition. Every index makes writes a little slower and takes disk space, so create indexes for real queries and remove the ones nobody uses.
In this lesson you will learn:
- what an index is and how a B-tree finds rows
- how to see a seq scan turn into an index scan with
EXPLAIN - composite indexes and the leftmost-column rule
- covering, partial, expression and unique indexes
- the PostgreSQL index types, the cost of indexes, and how to find unused ones
Before you start: Lesson 30, Normalization vs Denormalization: OLTP vs Analytics.
We ran every example on PostgreSQL 16.15 and checked the current PostgreSQL 18 manual; the SQL works on newer versions too. On PostgreSQL 18, EXPLAIN ANALYZE output also prints Buffers and Index Searches lines and shows rows with decimals (rows=12.00). Use the shop database from Lesson 3. Its four tables are too small for indexes to matter, so this lesson adds two practice tables and drops them at the end.
Table of Contents
Practice tables for this module
The script below creates big_customers (20,000 rows) and big_orders (200,000 rows) with generate_series (see Lesson 22) and random(). setseed makes the “random” series repeatable (PostgreSQL docs: Mathematical Functions), so the whole script, run in one session, gave us the same rows every time on PostgreSQL 16 (the docs do not promise the same series on other versions). VACUUM ANALYZE collects statistics for the planner.
DROP TABLE IF EXISTS big_orders, big_customers;
CREATE TABLE big_customers (
id integer PRIMARY KEY,
email text NOT NULL,
country text NOT NULL,
signup_date date NOT NULL
);
CREATE TABLE big_orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES big_customers (id),
order_date date NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL
);
SELECT setseed(0.31); -- fixed seed: everyone gets the same "random" data
INSERT INTO big_customers
SELECT i,
CASE WHEN i % 3 = 0 THEN 'Customer' || i || '@Example.com'
ELSE 'customer' || i || '@example.com' END,
(ARRAY['Pakistan','India','UK','USA','Canada','Germany','France','Italy'])[1 + floor(random() * 8)::int],
DATE '2023-01-01' + floor(random() * 1000)::int
FROM generate_series(1, 20000) AS i;
INSERT INTO big_orders
SELECT i,
1 + floor(random() * 20000)::int,
DATE '2024-01-01' + floor(random() * 1035)::int,
CASE WHEN r < 0.80 THEN 'delivered'
WHEN r < 0.90 THEN 'shipped'
WHEN r < 0.95 THEN 'cancelled'
ELSE 'pending' END,
round((5 + random() * 495)::numeric, 2)
FROM (SELECT i, random() AS r FROM generate_series(1, 200000) AS i) AS s;
VACUUM ANALYZE big_customers, big_orders;
DROP TABLE
CREATE TABLE
CREATE TABLE
setseed
---------
(1 row)
INSERT 0 20000
INSERT 0 200000
VACUUM
The first time, two NOTICE lines also say the tables do not exist yet; that is fine. Check the data:
SELECT COUNT(*) AS orders, COUNT(DISTINCT customer_id) AS customers,
MIN(order_date) AS first_day, MAX(order_date) AS last_day
FROM big_orders;
orders | customers | first_day | last_day
--------+-----------+------------+------------
200000 | 19999 | 2024-01-01 | 2026-10-31
(1 row)
What is a SQL index?
The PostgreSQL manual compares an index to the index at the back of a book: the reader can “scan the index relatively quickly and flip to the appropriate page(s), rather than having to read the entire book” (PostgreSQL docs: Indexes, Introduction). Without an index, the database must read the whole table, row by row.
The default index type is the B-tree (a “multi-way balanced tree”). Its leaf pages hold the indexed values in sorted order, and “each leaf page contains tuples that point to table rows”. Pages above the leaves point to the next level down (PostgreSQL docs: B-Tree Structure). To find one value, PostgreSQL starts at the root, follows one path down to a leaf, and then reads only the table pages that hold the matching rows.

Your shop tables already have indexes. A PRIMARY KEY or UNIQUE constraint (Lesson 16) creates a unique B-tree index automatically:
SELECT tablename, indexname, indexdef
FROM pg_indexes
WHERE tablename IN ('customers', 'products', 'orders', 'order_items')
ORDER BY tablename, indexname;
tablename | indexname | indexdef
-------------+---------------------+-----------------------------------------------------------------------------------------------
customers | customers_email_key | CREATE UNIQUE INDEX customers_email_key ON public.customers USING btree (email)
customers | customers_pkey | CREATE UNIQUE INDEX customers_pkey ON public.customers USING btree (id)
order_items | order_items_pkey | CREATE UNIQUE INDEX order_items_pkey ON public.order_items USING btree (order_id, product_id)
orders | orders_pkey | CREATE UNIQUE INDEX orders_pkey ON public.orders USING btree (id)
products | products_pkey | CREATE UNIQUE INDEX products_pkey ON public.products USING btree (id)
(5 rows)
Notice what is missing: orders.customer_id has no index. A foreign key (Lesson 28) “does not automatically create an index on the referencing columns” (PostgreSQL docs: Constraints).
Seq scan vs index scan
EXPLAIN shows the plan PostgreSQL picks for a query, without running it. Lesson 32 explains plans in detail; here we only look at the scan type. COSTS OFF hides the cost numbers.
EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE id = 4242;
QUERY PLAN
------------------------------------------------
Index Scan using big_orders_pkey on big_orders
Index Cond: (id = 4242)
(2 rows)
The primary key index finds order 4242 directly. Now search by customer:
EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE customer_id = 4242;
QUERY PLAN
--------------------------------
Seq Scan on big_orders
Filter: (customer_id = 4242)
(2 rows)
A Seq Scan (sequential scan) reads all 200,000 rows and keeps the 12 that match. Create an index and ask again:
CREATE INDEX big_orders_customer_id_idx ON big_orders (customer_id);
EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE customer_id = 4242;
CREATE INDEX
QUERY PLAN
-------------------------------------------------------
Bitmap Heap Scan on big_orders
Recheck Cond: (customer_id = 4242)
-> Bitmap Index Scan on big_orders_customer_id_idx
Index Cond: (customer_id = 4242)
(4 rows)
This is a bitmap scan, one way of using an index. PostgreSQL first reads the index and builds a map of the matching row locations, then visits those table rows “in physical order” (PostgreSQL docs: Combining Multiple Indexes). (The table is also called the heap.)
An index is not always used. If most rows match, reading the whole table in order is cheaper than jumping between index and table. About 75% of the orders have customer_id < 15000:
EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE customer_id < 15000;
QUERY PLAN
---------------------------------
Seq Scan on big_orders
Filter: (customer_id < 15000)
(2 rows)
The planner decides from statistics, which is why we ran ANALYZE; the manual notes you “might have to run the ANALYZE command regularly”.
Composite indexes and the leftmost-column rule
A composite (multicolumn) index sorts by the first column, then by the second inside each first value, like a phone book sorted by last name, then first name. Replace the single-column index with one on (customer_id, order_date):
DROP INDEX big_orders_customer_id_idx;
CREATE INDEX big_orders_cust_date_idx ON big_orders (customer_id, order_date);
EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE customer_id = 4242 AND order_date >= '2026-01-01';
EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE customer_id = 4242;
EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE order_date = '2026-03-15';
DROP INDEX
CREATE INDEX
QUERY PLAN
-----------------------------------------------------------------------------------
Bitmap Heap Scan on big_orders
Recheck Cond: ((customer_id = 4242) AND (order_date >= '2026-01-01'::date))
-> Bitmap Index Scan on big_orders_cust_date_idx
Index Cond: ((customer_id = 4242) AND (order_date >= '2026-01-01'::date))
(4 rows)
QUERY PLAN
-----------------------------------------------------
Bitmap Heap Scan on big_orders
Recheck Cond: (customer_id = 4242)
-> Bitmap Index Scan on big_orders_cust_date_idx
Index Cond: (customer_id = 4242)
(4 rows)
QUERY PLAN
---------------------------------------------
Seq Scan on big_orders
Filter: (order_date = '2026-03-15'::date)
(2 rows)
With both columns or only the first one, the index is used. With only the second column, it is not, just as a phone book sorted by last name cannot find everyone called “Sara”. The manual says an index is “most efficient when there are constraints on the leading (leftmost) columns” (PostgreSQL docs: Multicolumn Indexes). So the single index on customer_id is no longer needed. PostgreSQL 18 added skip scan, which can sometimes use later columns alone, but “generally only” when the first column has very few distinct values. The same page advises that multicolumn indexes “should be used sparingly”.
Covering indexes and index-only scans
Our query still visits the table to fetch total. A covering index stores extra columns in the index with INCLUDE. They are not part of the search key, but “an index-only scan can return the contents of non-key columns without having to visit the index’s table” (PostgreSQL docs: CREATE INDEX).
DROP INDEX big_orders_cust_date_idx;
CREATE INDEX big_orders_cust_date_idx ON big_orders (customer_id, order_date) INCLUDE (total);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_date, total FROM big_orders WHERE customer_id = 4242;
DROP INDEX
CREATE INDEX
QUERY PLAN
---------------------------------------------------------------------------------------
Index Only Scan using big_orders_cust_date_idx on big_orders (actual rows=12 loops=1)
Index Cond: (customer_id = 4242)
Heap Fetches: 0
(3 rows)
Heap Fetches: 0 means PostgreSQL did not have to fetch any rows from the table. This works because VACUUM filled the table’s visibility map. If a page has changed since the last vacuum, PostgreSQL must still check that page in the table (PostgreSQL docs: Index-Only Scans).
Partial and expression indexes
A partial index contains only “those table rows that satisfy the predicate” (PostgreSQL docs: Partial Indexes). Only 5% of orders are pending, so an index for them is small:
CREATE INDEX big_orders_pending_date_idx ON big_orders (order_date)
WHERE status = 'pending';
EXPLAIN (COSTS OFF)
SELECT id, order_date FROM big_orders
WHERE status = 'pending' AND order_date >= '2026-10-01';
CREATE INDEX
QUERY PLAN
-------------------------------------------------------------------------------------
Bitmap Heap Scan on big_orders
Recheck Cond: ((order_date >= '2026-10-01'::date) AND (status = 'pending'::text))
-> Bitmap Index Scan on big_orders_pending_date_idx
Index Cond: (order_date >= '2026-10-01'::date)
(4 rows)
The query must repeat the condition status = 'pending', or PostgreSQL cannot use the index. Compare its size with a full index on the same column:
CREATE INDEX big_orders_date_idx ON big_orders (order_date);
SELECT indexrelname AS index_name, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE indexrelname IN ('big_orders_pending_date_idx', 'big_orders_date_idx');
DROP INDEX big_orders_date_idx;
CREATE INDEX
index_name | size
-----------------------------+---------
big_orders_pending_date_idx | 112 kB
big_orders_date_idx | 1392 kB
(2 rows)
DROP INDEX
An expression index stores the result of a function. Our emails are in mixed case, so a case-insensitive search uses lower(email). There is no index for it yet, and a plain index on email would not help either:
EXPLAIN (COSTS OFF)
SELECT * FROM big_customers WHERE lower(email) = 'customer777@example.com';
QUERY PLAN
------------------------------------------------------------
Seq Scan on big_customers
Filter: (lower(email) = 'customer777@example.com'::text)
(2 rows)
Unique indexes
We index lower(email) and make it unique at the same time, so the same email cannot be stored twice in different letter case:
CREATE UNIQUE INDEX big_customers_lower_email_key ON big_customers (lower(email));
EXPLAIN (COSTS OFF)
SELECT * FROM big_customers WHERE lower(email) = 'customer777@example.com';
SELECT * FROM big_customers WHERE lower(email) = 'customer777@example.com';
INSERT INTO big_customers VALUES (20001, 'CUSTOMER777@EXAMPLE.COM', 'UK', '2026-11-01');
CREATE INDEX
QUERY PLAN
-----------------------------------------------------------------
Index Scan using big_customers_lower_email_key on big_customers
Index Cond: (lower(email) = 'customer777@example.com'::text)
(2 rows)
id | email | country | signup_date
-----+-------------------------+---------+-------------
777 | Customer777@Example.com | Canada | 2024-06-09
(1 row)
ERROR: duplicate key value violates unique constraint "big_customers_lower_email_key"
DETAIL: Key (lower(email))=(customer777@example.com) already exists.
Only B-tree indexes can be unique. By default, NULLs do not count as duplicates (see Lesson 6); NULLS NOT DISTINCT changes that (PostgreSQL docs: Unique Indexes).
PostgreSQL index types
CREATE INDEX makes a B-tree unless you add USING (PostgreSQL docs: Index Types):
| Type | Good for |
|---|---|
| B-tree (default) | =, <, >, BETWEEN, sorting, LIKE 'abc%' (C locale or text_pattern_ops only) |
| Hash | only = |
| GIN | values with many parts: arrays, JSONB, full-text search |
| GiST and SP-GiST | geometric data, ranges, nearest-neighbour searches |
| BRIN | huge tables where values follow the physical row order, such as log timestamps |
The cost of indexes
“After an index is created, the system has to keep it synchronized with the table”, which adds work to every INSERT, UPDATE and DELETE (Lesson 17). So “indexes that are seldom or never used in queries should be removed” (PostgreSQL docs: Indexes, Introduction). Indexes also take space:
SELECT pg_size_pretty(pg_table_size('big_orders')) AS table_size,
pg_size_pretty(pg_indexes_size('big_orders')) AS all_indexes;
table_size | all_indexes
------------+-------------
12 MB | 10 MB
(1 row)
Our three indexes on big_orders are almost as large as the table. Building an index also blocks writes to the table until it finishes; CREATE INDEX CONCURRENTLY avoids that, with some caveats listed in the docs.
Find unused indexes
pg_stat_user_indexes counts how often each index was used. idx_scan is the “number of index scans initiated on this index” (PostgreSQL docs: Cumulative Statistics):
SELECT relname AS table_name, indexrelname AS index_name, idx_scan
FROM pg_stat_user_indexes
WHERE relname IN ('big_orders', 'big_customers')
ORDER BY relname, indexrelname;
table_name | index_name | idx_scan
---------------+-------------------------------+----------
big_customers | big_customers_lower_email_key | 1
big_customers | big_customers_pkey | 200000
big_orders | big_orders_cust_date_idx | 1
big_orders | big_orders_pending_date_idx | 0
big_orders | big_orders_pkey | 0
(5 rows)
big_customers_pkey was used 200,000 times: the foreign key checked each new order against it during loading. Plain EXPLAIN does not run the query, so the pending index shows 0. On a real server, judge counts collected over weeks, and never drop an index behind a primary key or unique constraint. The counters update with a delay of up to a second.
Try it yourself
Run the practice-table script again if you dropped the tables.
Exercise 1: List the indexes
Show every index on big_orders and big_customers with its definition.
Exercise 2: A partial index for big cancelled orders
Create an index that helps SELECT id, total FROM big_orders WHERE status = 'cancelled' AND total > 490; and check the plan.
Exercise 3: An index-only scan
Create an index so that SELECT signup_date FROM big_customers WHERE country = 'Italy' AND signup_date >= '2025-09-01' becomes an index-only scan.
Solutions
Solution 1
SELECT tablename, indexname, indexdef
FROM pg_indexes
WHERE tablename IN ('big_orders', 'big_customers')
ORDER BY tablename, indexname;
tablename | indexname | indexdef
---------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------
big_customers | big_customers_lower_email_key | CREATE UNIQUE INDEX big_customers_lower_email_key ON public.big_customers USING btree (lower(email))
big_customers | big_customers_pkey | CREATE UNIQUE INDEX big_customers_pkey ON public.big_customers USING btree (id)
big_orders | big_orders_cust_date_idx | CREATE INDEX big_orders_cust_date_idx ON public.big_orders USING btree (customer_id, order_date) INCLUDE (total)
big_orders | big_orders_pending_date_idx | CREATE INDEX big_orders_pending_date_idx ON public.big_orders USING btree (order_date) WHERE (status = 'pending'::text)
big_orders | big_orders_pkey | CREATE UNIQUE INDEX big_orders_pkey ON public.big_orders USING btree (id)
(5 rows)
indexdef shows the INCLUDE and WHERE parts too.
Solution 2
CREATE INDEX big_orders_cancelled_total_idx ON big_orders (total)
WHERE status = 'cancelled';
EXPLAIN (COSTS OFF)
SELECT id, total FROM big_orders
WHERE status = 'cancelled' AND total > 490;
CREATE INDEX
QUERY PLAN
-----------------------------------------------------------------------------
Bitmap Heap Scan on big_orders
Recheck Cond: ((total > '490'::numeric) AND (status = 'cancelled'::text))
-> Bitmap Index Scan on big_orders_cancelled_total_idx
Index Cond: (total > '490'::numeric)
(4 rows)
The index holds only cancelled orders, sorted by total.
Solution 3
CREATE INDEX big_customers_country_signup_idx ON big_customers (country, signup_date);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT signup_date FROM big_customers
WHERE country = 'Italy' AND signup_date >= '2025-09-01';
CREATE INDEX
QUERY PLAN
--------------------------------------------------------------------------------------------------
Index Only Scan using big_customers_country_signup_idx on big_customers (actual rows=67 loops=1)
Index Cond: ((country = 'Italy'::text) AND (signup_date >= '2025-09-01'::date))
Heap Fetches: 0
(3 rows)
Both columns the query needs are in the index, with the equality column first.
When you finish, drop the practice tables (their indexes go with them):
DROP TABLE big_orders, big_customers;
DROP TABLE
Common mistakes
- Indexing a column, then wrapping it in a function. An index on
emaildoes not helpWHERE lower(email) = ...; index the expression instead. - Filtering only on the second column of a composite index. An index on
(customer_id, order_date)did not helpWHERE order_date = .... Put the column you filter by most often first. - Forgetting foreign key columns. PostgreSQL indexes the referenced primary key, not the referencing column.
- A unique index on a column with duplicates.
CREATE UNIQUE INDEX big_customers_country_key ON big_customers (country);fails withcould not create unique index "big_customers_country_key"andDETAIL: Key (country)=(USA) is duplicated. - Dropping a constraint’s index.
DROP INDEX big_orders_pkey;givescannot drop index big_orders_pkey because constraint big_orders_pkey on table big_orders requires it. Reusing a name givesrelation "big_orders_cust_date_idx" already exists.
Frequently asked questions
Does an index make every query faster?
No. It helps queries that read a small part of a table, and it costs write time and disk space. When a query reads most of the table, PostgreSQL ignores the index, as with customer_id < 15000.
How many indexes should a table have?
There is no fixed number. Index the primary key (automatic), foreign keys you join on, and the columns your frequent queries filter or sort by. Then check pg_stat_user_indexes and remove indexes that are never used.
Does PostgreSQL have clustered indexes?
Not in the way SQL Server does: a PostgreSQL table is stored separately from its indexes. The CLUSTER command reorders a table once by an index, but “clustering is a one-time operation”, and it locks the table while it runs (PostgreSQL docs: CLUSTER).
Summary
- A SQL index is a separate structure that points to table rows; PostgreSQL’s default, the B-tree, keeps values sorted.
- Primary keys and unique constraints create indexes automatically; foreign keys do not.
- A composite index works best when the query filters on its leftmost columns.
INCLUDEmakes covering indexes for index-only scans; partial and expression indexes index a subset or a computed value.- Every index slows writes and uses space; find unused ones with
pg_stat_user_indexes.
Next lesson
Next: Lesson 32, PostgreSQL EXPLAIN and EXPLAIN ANALYZE: Read a Query Plan.
Sources
- PostgreSQL documentation: Indexes, Introduction
- PostgreSQL documentation: Index Types
- PostgreSQL documentation: Multicolumn Indexes
- PostgreSQL documentation: Combining Multiple Indexes
- PostgreSQL documentation: Unique Indexes
- PostgreSQL documentation: Partial Indexes
- PostgreSQL documentation: Index-Only Scans and Covering Indexes
- PostgreSQL documentation: Indexes on Expressions
- PostgreSQL documentation: CREATE INDEX
- PostgreSQL documentation: B-Tree Indexes
- PostgreSQL documentation: Constraints
- PostgreSQL documentation: The Cumulative Statistics System
- PostgreSQL documentation: Mathematical Functions (random, setseed)
- PostgreSQL documentation: CLUSTER
- PostgreSQL documentation: Operator Classes (text_pattern_ops)
- PostgreSQL documentation: Using EXPLAIN (PostgreSQL 18 output)
- PostgreSQL 18 release notes (B-tree skip scan, EXPLAIN changes)





