Indexes

Topic 1 of 2 in Performance12 min readBeginnerFree course

Overview

On the twelve-row products table, every query is instant. Real tables have millions of rows, and a query that has to read all of them to find a handful becomes the slowest thing in your application. An index is a separate data structure that lets the database find rows without reading the whole table — like the index at the back of a book, which takes you straight to the right page instead of making you read every chapter.

Indexes are the single most important tool for database performance, and choosing them well is part of designing a database.

A table big enough to matter

To see indexes at work, we need volume. generate_series can create a 200,000-row table of synthetic orders in a fraction of a second:

SQL
CREATE TABLE big_orders AS
SELECT g AS id,
       (g * 7919) % 50000 + 1 AS customer_id,
       timestamp '2024-01-01' + (g % 1000) * interval '1 day'
                              + (g % 1440) * interval '1 minute' AS ordered_at,
       (ARRAY['pending','paid','shipped','delivered','delivered',
              'delivered','delivered','cancelled'])[g % 8 + 1] AS status,
       round((g % 9000) / 100.0 + 5, 2) AS total
FROM generate_series(1, 200000) AS g;

ALTER TABLE big_orders ADD PRIMARY KEY (id);
ANALYZE big_orders;
Text
SELECT 200000
ALTER TABLE
ANALYZE

ANALYZE collects statistics about the data, which the planner uses to choose between plans. (PostgreSQL also does this automatically in the background.)

Without an index: the sequential scan

Find one customer’s orders. EXPLAIN in front of a query shows the plan — how PostgreSQL intends to run it — without running it:

SQL
EXPLAIN SELECT * FROM big_orders WHERE customer_id = 4242;
Text
                          QUERY PLAN                          
--------------------------------------------------------------
 Seq Scan on big_orders  (cost=0.00..4100.00 rows=4 width=30)
   Filter: (customer_id = 4242)
(2 rows)

Seq Scan means a sequential scan: read every row of the table and test the condition on each. To return 4 rows, it examines 200,000. You’ll learn to read the numbers in the next lesson; for now, the cost estimate (4100) is what matters.

Creating an index

SQL
CREATE INDEX big_orders_customer_id_idx ON big_orders (customer_id);

EXPLAIN SELECT * FROM big_orders WHERE customer_id = 4242;
Text
CREATE INDEX
                                       QUERY PLAN                                        
-----------------------------------------------------------------------------------------
 Bitmap Heap Scan on big_orders  (cost=4.45..19.90 rows=4 width=30)
   Recheck Cond: (customer_id = 4242)
   ->  Bitmap Index Scan on big_orders_customer_id_idx  (cost=0.00..4.45 rows=4 width=0)
         Index Cond: (customer_id = 4242)
(4 rows)

Now the plan uses the index, and the estimated cost has dropped from 4,100 to about 20 — a 200-fold improvement. On real hardware, the query went from roughly 10 milliseconds to well under one. The query itself didn’t change: the planner noticed the index and chose it.

How a B-tree index works

How an index finds rows fast. A B-tree index on customer email: the root node splits the alphabet into a–d and e–h; below it are nodes for a–b, c–d, e–f and g–h; and at the bottom, sorted leaf entries asha@…, ben@…, chen@…, dee@…, elena@…, farhan@…, grace@… and hugo@…. To find grace@example.com, the search goes from the root to g–h and then to the grace@… leaf, which points to row 7 in the table. CREATE INDEX customers_email_idx ON customers (email) supports SELECT * FROM customers WHERE email = ‘grace@example.com’. Without an index, PostgreSQL reads every row in a sequential scan. A B-tree is a sorted tree: a few hops reach the row, even among millions. It helps =, <, >, BETWEEN, ORDER BY and LIKE ‘abc%’ on the indexed columns. Cost: disk space, and every INSERT or UPDATE must update the index too. Index what you search by, not everything.

The default index type is the B-tree: a balanced tree that keeps the indexed values sorted, with each leaf pointing at the table row that holds that value. Finding a value means walking from the root down a few levels — for a million rows, typically three or four hops — instead of scanning the whole table.

Because the values are sorted, a B-tree helps with much more than equality:

  • =, <, <=, >, >=, BETWEEN and IN;
  • ORDER BY on the indexed column (the rows can be read already in order), especially with LIMIT;
  • LIKE 'abc%' — a fixed prefix — on suitable text indexes;
  • IS NULL.

It can’t help with LIKE '%abc', or with conditions that wrap the column in a function (WHERE lower(email) = …) — unless the index is built on that same function, as you’ll see below.

Indexes you already have

Primary keys and UNIQUE constraints create indexes automatically — that’s how the database checks uniqueness quickly. The pg_indexes view lists them:

SQL
SELECT tablename, indexname
FROM pg_indexes
WHERE schemaname = 'public' AND tablename IN ('customers', 'orders', 'order_items')
ORDER BY tablename, indexname;
Text
  tablename  |      indexname      
-------------+---------------------
 customers   | customers_email_key
 customers   | customers_pkey
 order_items | order_items_pkey
 orders      | orders_pkey
(4 rows)

Notice what’s missing: there’s no index on orders.customer_id, even though it’s a foreign key. PostgreSQL doesn’t index foreign keys automatically, yet they’re used in almost every join — and when a customer is deleted, PostgreSQL must look up their orders to enforce the key. Index your foreign keys is one of the most valuable rules of thumb in database design.

Multi-column indexes

An index can cover several columns. Its rows are sorted by the first column, then by the second within the first, like a phone book sorted by surname then first name. Orders for one customer, newest first:

SQL
CREATE INDEX big_orders_customer_date_idx ON big_orders (customer_id, ordered_at);

EXPLAIN SELECT id, ordered_at, total
FROM big_orders
WHERE customer_id = 4242
ORDER BY ordered_at DESC
LIMIT 2;
Text
CREATE INDEX
                                                   QUERY PLAN                                                   
----------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.42..10.45 rows=2 width=18)
   ->  Index Scan Backward using big_orders_customer_date_idx on big_orders  (cost=0.42..20.49 rows=4 width=18)
         Index Cond: (customer_id = 4242)
(3 rows)

The index serves both the filter and the sort — the plan reads matching entries backwards and stops after two, with no separate sort step. The order of the columns matters: this index helps queries on customer_id, or on customer_id and ordered_at together, but not queries on ordered_at alone — just as a phone book sorted by surname doesn’t help you find everyone called “Asha”. A useful rule: equality columns first, then the range or sort column.

Unique, expression and partial indexes

A unique index enforces uniqueness, like a UNIQUE constraint. An expression index indexes the result of an expression — the fix for case-insensitive lookups:

SQL
CREATE UNIQUE INDEX customers_email_lower_idx ON customers (lower(email));

INSERT INTO customers (first_name, last_name, email, city, country, signup_date)
VALUES ('Asha', 'Rao', 'ASHA.RAO@example.com', 'Pune', 'India', '2026-12-04');
Text
CREATE INDEX
ERROR:  duplicate key value violates unique constraint "customers_email_lower_idx"
DETAIL:  Key (lower(email))=(asha.rao@example.com) already exists.

That index also speeds up WHERE lower(email) = lower($1), the query a login page runs — the expression in the query must match the expression in the index.

A partial index covers only the rows matching a condition. If the application constantly looks for pending orders, but they’re a small slice of the table, index just those:

SQL
CREATE INDEX big_orders_pending_idx ON big_orders (ordered_at)
WHERE status = 'pending';

EXPLAIN SELECT id, ordered_at FROM big_orders
WHERE status = 'pending' AND ordered_at >= '2026-09-01';
Text
CREATE INDEX
                                                     QUERY PLAN                                                      
---------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on big_orders  (cost=9.37..1244.98 rows=656 width=12)
   Recheck Cond: ((ordered_at >= '2026-09-01 00:00:00'::timestamp without time zone) AND (status = 'pending'::text))
   ->  Bitmap Index Scan on big_orders_pending_idx  (cost=0.00..9.21 rows=656 width=0)
         Index Cond: (ordered_at >= '2026-09-01 00:00:00'::timestamp without time zone)
(4 rows)

A partial index is smaller and cheaper to maintain than a full one, and it’s used whenever the query’s condition implies the index’s condition.

What indexes cost

Indexes aren’t free:

SQL
SELECT relname AS name,
       pg_size_pretty(pg_relation_size(oid)) AS size
FROM pg_class
WHERE relname LIKE 'big_orders%'
ORDER BY relname;
Text
             name             |  size   
------------------------------+---------
 big_orders                   | 13 MB
 big_orders_customer_date_idx | 6184 kB
 big_orders_customer_id_idx   | 2432 kB
 big_orders_pending_idx       | 296 kB
 big_orders_pkey              | 4408 kB
(5 rows)
  • Space: the indexes on big_orders together are a substantial fraction of the size of the table itself.
  • Slower writes: every INSERT, every DELETE, and every UPDATE that changes an indexed column must update each index as well.
  • Not always used: on small tables, or when a query matches a large share of the rows, reading the table sequentially is faster, and the planner will ignore the index. An index on status — eight values spread over 200,000 rows — would rarely help.

So index deliberately: columns you filter on (WHERE), join on (foreign keys), and sort on (ORDER BY … LIMIT), in queries that run often or must be fast.

Managing indexes

SQL
DROP INDEX big_orders_pending_idx;
Text
DROP INDEX

In psql, \di lists indexes and \d tablename shows a table’s indexes. On a busy production table, CREATE INDEX blocks writes until it finishes; CREATE INDEX CONCURRENTLY builds the index without blocking (more slowly, and not inside a transaction). Other index types exist for special data — GIN for JSON, arrays and full-text search, GiST for geometry and ranges, BRIN for huge, naturally ordered tables — but B-tree is the right choice most of the time.

Tip: don’t guess which indexes to add. Find the slow queries (PostgreSQL’s pg_stat_statements extension records them), look at their plans with EXPLAIN ANALYZE, and index for what you see — that’s the next lesson.

Exercise

Index the shop

Three indexes for Bean & Leaf. First, create a unique index named customers_email_lower_idx on lower(email), so that no two customers can share an email in any capitalisation — then prove it by trying to insert a customer with the email Asha.Rao@Example.com (it must fail). Second, index the foreign key orders.customer_id with an index named orders_customer_id_idx. Third, list the indexname of every index on the orders table from the pg_indexes view, ordered by name.

SQL
-- 1. Case-insensitive unique emails, then test it

-- 2. Index orders.customer_id

-- 3. List the indexes on orders

Summary

  • Without an index, PostgreSQL must read every row (a sequential scan); an index lets it jump straight to the matching rows.
  • The default B-tree index keeps values sorted, so it helps =, <, >, BETWEEN, ORDER BY and LIKE 'prefix%'.
  • Primary keys and UNIQUE constraints get indexes automatically; foreign keys don't, and usually should be indexed.
  • Multi-column indexes work left to right; expression indexes (lower(email)) and partial indexes (WHERE status = 'pending') target specific queries.
  • Indexes cost disk space and slow down writes, so index the columns you actually search, join and sort by.