Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 17 / Stage 4

Indexing

Goal: The biggest read-performance lever, used precisely — how B-trees work and what they can serve, composite column order, partial, expression and covering indexes, the specialist types (GIN, GiST, BRIN, Hash), what every index costs, and how to build one without stopping the world. Time: ~2.5 hours

What you will learn

  • How a B-tree index works, and which operators it serves
  • Composite indexes: why column order decides everything
  • Partial indexes: indexing only the rows you query
  • Expression indexes: lower(email) and friends
  • Covering indexes: INCLUDE for index-only scans
  • GIN, GiST, BRIN and Hash — which data each fits
  • The cost of indexes: writes, storage, and finding dead weight
  • CREATE INDEX CONCURRENTLY

The lab: 100,000 users with mixed-case emails —

CREATE TABLE big_users AS
SELECT g AS id,
       'User' || g || '@Example.com' AS email,
       CASE WHEN g % 20 = 0 THEN 'pending' ELSE 'done' END AS status,
       DATE '2024-01-01' + (g % 365) AS joined_on
FROM generate_series(1, 100000) AS g;
ANALYZE big_users;
SELECT 100000
ANALYZE

Topics in this part

Practice

SQL workbench — write and run queries here

Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.

Design first, verify with EXPLAIN second. Solutions are re-runnable and build their own lab tables (run ex01 first — ex02, ex04 and ex05 reuse its tickets).


Exercise 1: Design the composite

Scenario: A 100k-row tickets table; the hot query is "agent 7's open tickets since October" — two equalities and a range. What to do: Build the table, design the one composite index that serves the query best, and prove with EXPLAIN that all three conditions land in the Index Cond.

Sample output:

 Bitmap Heap Scan on tickets
   Recheck Cond: ((agent_id = 7) AND (status = 'open'::text) AND (opened_on > '2024-10-01'::date))
   ->  Bitmap Index Scan on idx_tickets_hot
         Index Cond: ((agent_id = 7) AND (status = 'open'::text) AND (opened_on > '2024-10-01'::date))
(4 rows)

💡 Hint: equalities first, range last: (agent_id, status, opened_on).


Show the solution to Exercise 1
-- Exercise 1: Design the composite (re-runnable)
DROP TABLE IF EXISTS tickets;
CREATE TABLE tickets AS
SELECT g AS id,
       (g % 200) + 1 AS agent_id,
       CASE WHEN g % 10 = 0 THEN 'open' ELSE 'closed' END AS status,
       DATE '2024-01-01' + (g % 365) AS opened_on
FROM generate_series(1, 100000) AS g;
ANALYZE tickets;
-- The hot query: an agent's open tickets since a date.
-- Equality columns first (agent_id, status), range (opened_on) last:
CREATE INDEX idx_tickets_hot ON tickets (agent_id, status, opened_on);
ANALYZE tickets;
EXPLAIN (COSTS OFF)
SELECT * FROM tickets
WHERE agent_id = 7 AND status = 'open' AND opened_on > DATE '2024-10-01';

Exercise 2: The conditional unique

What to do: Enforce "an agent may have at most one open escalated ticket" — no trigger, one index. Prove it by escalating two open tickets for the same agent.

Sample output (the proof):

ERROR:  duplicate key value violates unique constraint "idx_one_open_escalation"
DETAIL:  Key (agent_id)=(11) already exists.

💡 Hint: CREATE UNIQUE INDEX ... ON tickets (agent_id) WHERE status = 'open' AND escalated;


Show the solution to Exercise 2
-- Exercise 2: The conditional unique (re-runnable; needs ex01's tickets)
-- "An agent may have at most one open escalation."
ALTER TABLE tickets ADD COLUMN IF NOT EXISTS escalated boolean NOT NULL DEFAULT false;
DROP INDEX IF EXISTS idx_one_open_escalation;
CREATE UNIQUE INDEX idx_one_open_escalation
ON tickets (agent_id) WHERE status = 'open' AND escalated;
UPDATE tickets SET escalated = true WHERE id = 10;      -- agent 11's open ticket
-- A second open escalation for the same agent is refused:
UPDATE tickets SET escalated = true, status = 'open', agent_id = 11 WHERE id = 20;

Exercise 3: The case-insensitive login

What to do: Reproduce the classic mystery — an indexed email column, a lower(email) = ... query, a seq scan — then fix it with the matching expression index and show the plan flip.

💡 Hint: the index must store the exact expression the query computes: (lower(email)).


Show the solution to Exercise 3
-- Exercise 3: The case-insensitive login (re-runnable)
DROP TABLE IF EXISTS big_users;
CREATE TABLE big_users AS
SELECT g AS id, 'User' || g || '@Example.com' AS email
FROM generate_series(1, 100000) AS g;
CREATE INDEX idx_users_email ON big_users (email);
ANALYZE big_users;
-- The index that exists doesn't match the expression the query computes:
EXPLAIN (COSTS OFF) SELECT * FROM big_users WHERE lower(email) = '[email protected]';
-- Index the expression itself:
CREATE INDEX idx_users_email_lower ON big_users (lower(email));
ANALYZE big_users;
EXPLAIN (COSTS OFF) SELECT * FROM big_users WHERE lower(email) = '[email protected]';

Exercise 4: Cover the hot read

What to do: The dashboard asks only SELECT opened_on FROM tickets WHERE status = 'open' a thousand times a minute. Build the index that answers it without touching the heap, and show the plan that proves it.

Sample output:

 Index Only Scan using idx_tickets_cover on tickets
   Index Cond: (status = 'open'::text)
(2 rows)

💡 Hint: (status) INCLUDE (opened_on), then VACUUM so the visibility map lets the heap be skipped.


Show the solution to Exercise 4
-- Exercise 4: Cover the hot read (re-runnable; needs ex01's tickets)
DROP INDEX IF EXISTS idx_tickets_cover;
CREATE INDEX idx_tickets_cover ON tickets (status) INCLUDE (opened_on);
VACUUM tickets;
EXPLAIN (COSTS OFF)
SELECT opened_on FROM tickets WHERE status = 'open';
-- Index Only Scan: key filters, INCLUDE payload answers, heap untouched.

Exercise 5: The index audit

What to do: List every index on tickets with its size and idx_scan, then deliver a one-line verdict per index: keep, drop, or "it's a constraint — scans don't apply".

💡 Hint: pg_stat_user_indexes joined by relname; remember EXPLAIN-only queries never increment idx_scan, and unique partial indexes are rules, not accelerators.

Show the solution to Exercise 5
-- Exercise 5: The index audit (re-runnable; needs ex01's tickets)
-- Size per index, and whether anything has ever used it:
SELECT i.indexrelname,
       pg_size_pretty(pg_relation_size(i.indexrelid)) AS size,
       i.idx_scan
FROM pg_stat_user_indexes AS i
WHERE i.relname = 'tickets'
ORDER BY pg_relation_size(i.indexrelid) DESC;
-- Verdicts (comment answers): idx_tickets_hot earns its keep on the hot
-- query; the covering index only if that read is truly hot; the unique
-- partial index is a CONSTRAINT and may never show scans - it stays.

Common mistakes

Mistake What happens Fix
Range column leading a composite Equality queries crawl Equality first, range after
Index on email, query on lower(email) Index ignored, seq scans Expression index — match the query's expression
Index per column "just in case" Write amplification, dead weight Design from query shapes; audit idx_scan
BRIN on scattered data Index maintained, nothing pruned BRIN only where order correlates physically
CREATE INDEX on a hot table at noon Writes blocked for the build CONCURRENTLY, standalone
Dropping a "unused" unique index A constraint quietly vanished Check what the index enforces first

Quick recap

  • B-trees are shallow and sorted, which is why they serve =, ranges, prefixes, ORDER BY and min/max — and never %middle% or transformed columns.
  • In a composite index, equality columns lead and the range column follows; (a,b) also covers queries on (a) alone.
  • A partial index covers just the queried slice (and gives conditional uniqueness), an expression index stores what the query computes, and INCLUDE carries payload columns for index-only scans.
  • GIN answers "contains", GiST answers "overlaps", BRIN summarises physical order, and Hash handles plain equality.
  • Every index taxes writes and disk — audit idx_scan, drop dead weight.
  • Indexes on live tables are built with CONCURRENTLY, run standalone, with a retry plan ready.

Checklist

Before Part 18, make sure you can:

  • List what a B-tree can and cannot serve, with the why.
  • Order a composite index for status = X AND created_at > Y and defend it.
  • Write the partial unique index for "one active per user".
  • Fix the lower(email) mystery both ways.
  • Say when BRIN's kilobytes beat a B-tree's megabytes — and when they don't.
  • Recite the CONCURRENTLY contract: why, where it can't run, what a failure leaves.

Read more: the official indexes chapter and index types section.

Search the guide