Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 3

Lab: Designing Indexes for a Workload, Text Search Included

Measure four real query patterns on the two-million-order shop dataset, design a composite, a covering, a partial and two GIN indexes for them, and price every index in write throughput.

Contentsand lesson path

What you will learn

  • Choose B-tree, composite, partial, covering or expression indexes (and recognize when GIN or BRIN fit, including GIN for full-text and trigram search) for a query pattern, accounting for write overhead.

Prerequisites: SQL Fundamentals

01. Goal and setup

Indexes are designed for a workload, never for a table. Here that is four query patterns a shop backend runs, plus the write pattern that pays for them:

  • W1, order history — one customer's orders since August, newest first. Hot path, thousands of calls a day.
  • W2, ops dashboard — all pending orders created before October, ordered by date. Runs every few minutes.
  • W3, customer page — that customer's five latest orders with their totals.
  • W4, product search — substring match on product names, and ranked full-text search. User-facing, latency-sensitive.
  • The bill — a continuous stream of inserts into orders.

You need: the qopt-lab container with the qopt database loaded in the previous lesson, and Python 3.12 or newer with psycopg for step 6 (uv venv && uv pip install "psycopg[binary]==3.3.9"; the lab was tested with psycopg 3.3.9 on Python 3.12).

Outputs that print timings are Illustrative output from one run on a four-core desktop: your milliseconds will differ, and so will the planner's estimates, because ANALYZE samples rows at random. Each step also ends with an Expected output you can match exactly: the same query under EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF), which keeps the plan shape and the real row counts (the data has a fixed seed) and drops everything that varies.

02. Step 1: measure before you design

Run each pattern under EXPLAIN (ANALYZE, BUFFERS). W1 first — note that the index from the previous lesson, orders(created_at), exists but does not fit this query:

SQL · qopt=#
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total, created_at FROM orders
WHERE customer_id = 4242
  AND created_at >= timestamptz '2026-08-01'
ORDER BY created_at DESC;
Illustrative output (abridged; timings vary by machine)
Gather Merge  (cost=25938.58..25939.04 rows=4 width=22)
  (actual time=86.165..89.691 rows=4 loops=1)
  Workers Planned: 2
  ->  Sort  (cost=24938.55..24938.56 rows=2 width=22)
        (actual time=61.108..61.110 rows=1 loops=3)
        Sort Key: created_at DESC
        ->  Parallel Bitmap Heap Scan on orders
              (cost=4994.85..24938.54 rows=2 width=22)
              (actual time=42.371..61.058 rows=1 loops=3)
              Recheck Cond: (created_at >= '2026-08-01 ...'::
                timestamp with time zone)
              Filter: (customer_id = 4242)
              Rows Removed by Filter: 91324
              Heap Blocks: exact=7109
              ->  Bitmap Index Scan on orders_created_idx
                    (cost=0.00..4994.85 rows=270190 width=0)
                    (actual time=24.816..24.816 rows=273976 loops=1)
                    Index Cond: (created_at >= '2026-08-01 ...'::
                      timestamp with time zone)
Planning Time: 0.655 ms
Execution Time: 89.806 ms

Read what happened: the date index found 273,976 candidate orders, the heap scan visited roughly 18,000 pages across three processes (exact=7109 is only the leader's share; random dates put candidates on nearly every page), and then a Filter hunted for customer 4242 and discarded 91,324 rows per process — to return 4 rows in about 90 ms. The index matches the range column, but the selectivity lives in customer_id: the wrong shape for this query.

Now measure W2 and W4 the same way, so that steps 4 and 5 have a baseline:

SQL · qopt=#
EXPLAIN (ANALYZE)
SELECT id, customer_id, created_at FROM orders
WHERE status = 'pending' AND created_at < timestamptz '2026-10-01'
ORDER BY created_at;

EXPLAIN (ANALYZE)
SELECT id, name, price FROM products
 WHERE name ILIKE '%less mo%';

EXPLAIN (ANALYZE)
SELECT id, name, price FROM products
 WHERE to_tsvector('english', name)
         @@ websearch_to_tsquery('english', 'wireless mouse')
 ORDER BY ts_rank(to_tsvector('english', name),
         websearch_to_tsquery('english', 'wireless mouse')) DESC
LIMIT 10;
Illustrative output (heavily abridged; timings vary by machine)
Gather Merge  (cost=32579.10..35413.59 rows=24294 width=24)
  (actual time=99.915..109.524 rows=28504 loops=1)
  ->  Parallel Seq Scan on orders  (... rows=9501 loops=3)
        Rows Removed by Filter: 657165
Execution Time: 110.794 ms

Seq Scan on products  (cost=0.00..4596.00 rows=4420 width=41)
  (actual time=0.048..184.876 rows=4444 loops=1)
  Filter: (name ~~* '%less mo%'::text)
  Rows Removed by Filter: 195556
Execution Time: 185.093 ms

Limit  (cost=33979.14..33979.49 rows=3 width=45)
  (actual time=822.499..824.724 rows=10 loops=1)
  ->  Gather Merge  ...
        ->  Parallel Seq Scan on products  (... rows=1111 loops=2)
              Rows Removed by Filter: 98889
Execution Time: 824.772 ms

All three are sequential scans at this point: about 110 ms for the pending dashboard (28,504 rows kept from two million), 185 ms for name ILIKE '%less mo%', and 825 ms for the ranked full-text query, which computed to_tsvector for all 200,000 product names. Record what W1 returns, to check later that indexes change only how the answer is found:

SQL · qopt=#
SELECT id, total, created_at FROM orders
WHERE customer_id = 4242
  AND created_at >= timestamptz '2026-08-01'
ORDER BY created_at DESC;
Expected output
   id    | total  |          created_at           
---------+--------+-------------------------------
 1516907 |  84.06 | 2026-10-20 04:56:05.848286+00
 1780229 |  94.71 | 2026-09-18 21:56:45.276232+00
  882601 | 451.08 | 2026-08-18 20:44:57.373786+00
  822600 | 110.73 | 2026-08-17 07:50:59.719747+00
(4 rows)

03. Step 2: the composite index — equality first, range second

W1 fixes one customer, then ranges over dates, then sorts by the same date. A single B-tree on both columns, equality column first, serves all three: inside each key the date is stored after the customer, so the entries of each customer are already in date order and ORDER BY ... DESC becomes a backward walk with no Sort node:

SQL · qopt=#
CREATE INDEX orders_customer_created_idx
  ON orders (customer_id, created_at);
ANALYZE orders;

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total, created_at FROM orders
WHERE customer_id = 4242
  AND created_at >= timestamptz '2026-08-01'
ORDER BY created_at DESC;
Illustrative output (timings vary by machine)
Index Scan Backward using orders_customer_created_idx on orders
  (cost=0.43..24.53 rows=5 width=22)
  (actual time=0.039..0.052 rows=4 loops=1)
  Index Cond: ((customer_id = 4242)
    AND (created_at >= '2026-08-01 00:00:00+00'::
    timestamp with time zone))
  Buffers: shared hit=9 read=4
Planning Time: 0.201 ms
Execution Time: 0.084 ms

About 90 ms down to under 0.1 ms, and the whole descent touched thirteen pages. The Index Cond now carries both predicates: the tree navigates to customer 4242, then walks dates. Reversing the column order (created_at, customer_id) would break this: each customer's rows would scatter across the whole date range. Confirm the plan shape without the timings:

SQL · qopt=#
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, total, created_at FROM orders
WHERE customer_id = 4242
  AND created_at >= timestamptz '2026-08-01'
ORDER BY created_at DESC;
Expected output (long lines wrapped)
 Index Scan Backward using orders_customer_created_idx on orders
   (actual rows=4 loops=1)
   Index Cond: ((customer_id = 4242) AND (created_at >=
     '2026-08-01 00:00:00+00'::timestamp with time zone))

04. Step 3: the covering index — answers without the heap

W3 needs id, total and created_at for five rows. The composite index from step 2 finds them, but total is not in that index, so every row still costs a heap visit. INCLUDE appends payload columns to leaf entries without making them part of the sort key:

SQL · qopt=#
CREATE INDEX orders_customer_latest_idx
  ON orders (customer_id, created_at DESC)
  INCLUDE (id, total);
VACUUM (ANALYZE) orders;

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total, created_at FROM orders
WHERE customer_id = 4242
ORDER BY created_at DESC
LIMIT 5;
Illustrative output (timings vary by machine)
Limit  (cost=0.43..1.00 rows=5 width=22)
  (actual time=0.075..0.079 rows=5 loops=1)
  Buffers: shared hit=4 read=3
  ->  Index Only Scan using orders_customer_latest_idx on orders
        (cost=0.43..5.15 rows=41 width=22)
        (actual time=0.074..0.076 rows=5 loops=1)
        Index Cond: (customer_id = 4242)
        Heap Fetches: 0
        Buffers: shared hit=4 read=3
Planning Time: 0.325 ms
Execution Time: 0.117 ms
SQL · qopt=#
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, total, created_at FROM orders
WHERE customer_id = 4242
ORDER BY created_at DESC
LIMIT 5;
Expected output (long lines wrapped)
 Limit (actual rows=5 loops=1)
   ->  Index Only Scan using orders_customer_latest_idx on orders
         (actual rows=5 loops=1)
         Index Cond: (customer_id = 4242)
         Heap Fetches: 0

Index Only Scan, Heap Fetches: 0, seven pages total. The VACUUM matters: it marks the table's pages all-visible in the visibility map, the condition that lets the planner trust index entries alone (the first lesson showed the mechanism). But look at the price list before you keep both indexes:

SQL · qopt=#
SELECT relname, pg_size_pretty(pg_relation_size(oid)) AS size
FROM pg_class
WHERE relname LIKE 'orders%' AND relkind IN ('r', 'i')
ORDER BY pg_relation_size(oid) DESC;
Expected output
           relname           |  size  
-----------------------------+--------
 orders                      | 143 MB
 orders_customer_latest_idx  | 95 MB
 orders_customer_created_idx | 60 MB
 orders_created_idx          | 43 MB
 orders_pkey                 | 43 MB
(5 rows)

Two overlapping indexes now serve almost the same queries, at 155 MB combined and double the write maintenance. In production you would keep only the covering index, which also serves W1. This lab keeps both because later steps still contrast them.

05. Step 4: the partial index — index only the interesting rows

W2 only ever asks for pending orders — 1.5% of the table, and everything else is history no dashboard queries. A partial index stores just those rows, with the same predicate written into the index definition:

SQL · qopt=#
CREATE INDEX orders_pending_created_idx ON orders (created_at)
  WHERE status = 'pending';
ANALYZE orders;

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, customer_id, created_at FROM orders
WHERE status = 'pending' AND created_at < timestamptz '2026-10-01'
ORDER BY created_at;
Illustrative output (abridged; timings vary by machine)
Sort  (cost=22119.37..22189.16 rows=27918 width=24)
  (actual time=59.681..63.716 rows=28504 loops=1)
  Sort Key: created_at
  Sort Method: quicksort  Memory: 1882kB
  ->  Bitmap Heap Scan on orders
        (cost=540.65..20057.77 rows=27918 width=24)
        (actual time=5.017..51.544 rows=28504 loops=1)
        Recheck Cond: ((created_at < '2026-10-01 ...'::
          timestamp with time zone)
          AND (status = 'pending'::text))
        Heap Blocks: exact=14475
        ->  Bitmap Index Scan on orders_pending_created_idx
              (cost=0.00..533.67 rows=27918 width=0)
              (actual time=3.284..3.285 rows=28504 loops=1)
              Index Cond: (created_at < '2026-10-01 ...'::
                timestamp with time zone)
Planning Time: 0.235 ms
Execution Time: 65.616 ms
SQL · qopt=#
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, customer_id, created_at FROM orders
WHERE status = 'pending' AND created_at < timestamptz '2026-10-01'
ORDER BY created_at;
Expected output (long lines wrapped)
 Sort (actual rows=28504 loops=1)
   Sort Key: created_at
   Sort Method: quicksort  Memory: 1882kB
   ->  Bitmap Heap Scan on orders (actual rows=28504 loops=1)
         Recheck Cond: ((created_at < '2026-10-01 00:00:00+00'::timestamp
           with time zone) AND (status = 'pending'::text))
         Heap Blocks: exact=14475
         ->  Bitmap Index Scan on orders_pending_created_idx
               (actual rows=28504 loops=1)
               Index Cond: (created_at < '2026-10-01 00:00:00+00'::timestamp
                 with time zone)

The index found all 28,504 pending orders in about 3 ms; the rest is fetching 14,475 heap pages of rows the query really returns, so this pattern is near its floor. Run the size query from step 3 again: orders_pending_created_idx | 672 kB, 672 kB against 43 MB for a full index on created_at, and inserts of completed orders never touch it. The planner uses it only when it can prove the query's predicate implies the index predicate: here status = 'pending' matches the index's WHERE clause.

07. Step 6: price the indexes in write throughput

Every index above is maintained on every write. The script creates two copies of the orders shape, one bare and one carrying the three secondary indexes from steps 2–4, bulk-loads 100,000 rows into each with COPY, then times 2,000 single-row inserts into each. It drops and recreates both copies, so you can run it again. Save it as 03-write-cost.py and run uv run python 03-write-cost.py:

Python · 03-write-cost.py
import io, statistics, time
from datetime import datetime, timedelta, timezone
import psycopg

DSN = "host=localhost port=55461 dbname=qopt user=lab password=lab"
N_BULK, N_ROWS = 100_000, 2_000

DDL = """
DROP TABLE IF EXISTS orders_plain, orders_indexed;
CREATE TABLE orders_plain (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id bigint NOT NULL,
  status      text NOT NULL,
  total       numeric(10,2) NOT NULL,
  created_at  timestamptz NOT NULL
);
CREATE TABLE orders_indexed (LIKE orders_plain INCLUDING ALL);
CREATE INDEX ON orders_indexed (customer_id, created_at);
CREATE INDEX ON orders_indexed (customer_id, created_at DESC)
  INCLUDE (id, total);
CREATE INDEX ON orders_indexed (created_at) WHERE status = 'pending';
"""

def gen_rows(n, id_offset=0):
    base = datetime(2026, 11, 1, tzinfo=timezone.utc)
    for i in range(n):
        yield (str(i % 50_000 + 1),
               'pending' if i % 67 == 0 else 'completed',
               f"{9.90 + (i * 7) % 480:.2f}",
               (base + timedelta(seconds=i + id_offset)).isoformat())

def bulk_copy(cur, table, n, id_offset=0):
    buf = io.StringIO()
    for row in gen_rows(n, id_offset):
        buf.write("\t".join(row) + "\n")
    buf.seek(0)
    t0 = time.perf_counter()
    with cur.copy(  # COPY is the fast path for bulk loads
        f"COPY {table} (customer_id, status, total, created_at)"
        " FROM STDIN") as cp:
        cp.write(buf.read())
    return time.perf_counter() - t0

def single_inserts(cur, table, n, id_offset=0):
    rows = list(gen_rows(n, id_offset))
    stmt = (f"INSERT INTO {table} (customer_id, status, total,"
            " created_at) VALUES (%s, %s, %s, %s)")
    t0 = time.perf_counter()
    for row in rows:          # one round trip per row
        cur.execute(stmt, row)
    return time.perf_counter() - t0

with psycopg.connect(DSN) as conn:
    with conn.cursor() as cur:
        cur.execute(DDL)      # no parameters, so several statements are fine
        conn.commit()
        plain_copy = bulk_copy(cur, "orders_plain", N_BULK)
        indexed_copy = bulk_copy(cur, "orders_indexed", N_BULK, 1_000)
        conn.commit()
        plain_one = statistics.median(
            single_inserts(cur, "orders_plain", N_ROWS,
                           r * N_ROWS) for r in range(3))
        indexed_one = statistics.median(
            single_inserts(cur, "orders_indexed", N_ROWS,
                           (r + 10) * N_ROWS) for r in range(3))

print(f"bulk COPY of {N_BULK:,} rows")
print(f"  no secondary indexes : {plain_copy:6.2f} s"
      f"  ({N_BULK / plain_copy:,.0f} rows/s)")
print(f"  3 secondary indexes  : {indexed_copy:6.2f} s"
      f"  ({N_BULK / indexed_copy:,.0f} rows/s)")
print(f"single-row INSERTs x {N_ROWS:,}"
      " (one round trip per row, median of 3)")
print(f"  no secondary indexes : {plain_one:6.2f} s")
print(f"  3 secondary indexes  : {indexed_one:6.2f} s")
Illustrative output (one run on a 4-core desktop; your timings will differ)
bulk COPY of 100,000 rows
  no secondary indexes :   0.34 s  (295,153 rows/s)
  3 secondary indexes  :   0.83 s  (119,953 rows/s)
single-row INSERTs x 2,000 (one round trip per row, median of 3)
  no secondary indexes :   0.23 s
  3 secondary indexes  :   0.25 s

Bulk-load throughput fell noticeably (to under half on this run). Single-row latency barely moved, because the index work per row is microseconds and the round trip is hundreds: index cost shows up as sustained load on bulk paths, not as per-request latency. Submit this measurement with any index proposal: milliseconds saved per query, rows per second lost per write. The row counts, unlike the timings, are exact:

SQL · qopt=#
SELECT (SELECT count(*) FROM orders_plain)   AS plain_rows,
       (SELECT count(*) FROM orders_indexed) AS indexed_rows;
Expected output
 plain_rows | indexed_rows 
------------+--------------
     106000 |       106000
(1 row)

08. Step 7: BRIN — when data arrives in order

Event tables grow append-only and are queried by time range; a B-tree over billions of events would be enormous. BRIN (Block Range Index) stores, for each run of adjacent table pages, just the minimum and maximum of the indexed column — a few dozen bytes per range. It works only when the column's values follow the physical row order, which append-only timestamps do. Try it on five million one-per-second sensor readings:

SQL · qopt=# (load takes about 30 s)
CREATE UNLOGGED TABLE events (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  sensor     int  NOT NULL,
  reading    numeric(8,2) NOT NULL,
  created_at timestamptz NOT NULL
);

INSERT INTO events (sensor, reading, created_at)
SELECT (g % 50) + 1,
       round((random() * 100)::numeric, 2),
       timestamptz '2026-01-01' + (g * interval '1 second')
FROM generate_series(1, 5000000) g;

CREATE INDEX events_created_brin ON events USING brin (created_at);
ANALYZE events;

EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*), avg(reading) FROM events
 WHERE created_at >= timestamptz '2026-01-20 12:00:00+00'
   AND created_at <  timestamptz '2026-01-20 13:00:00+00';
Illustrative output (abridged; timings vary by machine)
Aggregate  (cost=30427.03..30427.04 rows=1 width=40)
  (actual time=3.730..3.731 rows=1 loops=1)
  ->  Bitmap Heap Scan on events
        (cost=12.86..30410.54 rows=3299 width=6)
        (actual time=2.348..3.238 rows=3600 loops=1)
        Recheck Cond: (created_at >= ... AND created_at < ...)
        Rows Removed by Index Recheck: 13808
        Heap Blocks: lossy=128
        ->  Bitmap Index Scan on events_created_brin
              (cost=0.00..12.03 rows=17361 width=0)
              (actual time=0.108..0.109 rows=1280 loops=1)
              Index Cond: (created_at >= ... AND created_at < ...)
Planning Time: 0.389 ms
Execution Time: 3.772 ms
SQL · qopt=#
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*), avg(reading) FROM events
 WHERE created_at >= timestamptz '2026-01-20 12:00:00+00'
   AND created_at <  timestamptz '2026-01-20 13:00:00+00';

SELECT pg_size_pretty(pg_relation_size('events_created_brin'))
  AS brin_size;
Expected output (long lines wrapped)
 Aggregate (actual rows=1 loops=1)
   ->  Bitmap Heap Scan on events (actual rows=3600 loops=1)
         Recheck Cond: ((created_at >= '2026-01-20 12:00:00+00'::timestamp
           with time zone) AND (created_at < '2026-01-20 13:00:00+00'::timestamp
           with time zone))
         Rows Removed by Index Recheck: 13808
         Heap Blocks: lossy=128
         ->  Bitmap Index Scan on events_created_brin (actual rows=1280 loops=1)
               Index Cond: ((created_at >= '2026-01-20 12:00:00+00'::timestamp
                 with time zone) AND (created_at <
                 '2026-01-20 13:00:00+00'::timestamp with time zone))

 brin_size 
-----------
 24 kB
(1 row)

Under four milliseconds for an hour of readings, and the index is 24 kB. A B-tree (CREATE INDEX ON events (created_at), then drop it again) answers in a similar time, depending on caching, but weighs 107 MB and costs far more per insert. BRIN loses precision: it can only say this range of pages may contain matching rows, so the heap scan rechecks every row in those pages (Heap Blocks: lossy=128, Rows Removed by Index Recheck: 13808). Its rows=1280 is only a convention of ten per page for one 128-page range (the default pages_per_range). BRIN also fails when insertion order and value order diverge: randomly ordered orders.created_at would be a misuse; an append-only time series is its home ground.

09. Troubleshooting

10. Check your understanding

Practice check · 3 questions

Choosing index shapes

Three design decisions from this lab.

Q1. A partial index is declared `ON events (created_at) WHERE level = 'error'`. Which query can the planner serve from it?
Q2. A query selects `id, total, created_at` for one customer and gets an Index Only Scan with `Heap Fetches: 0`. What made that possible?
Q3. A GIN index exists on `to_tsvector('english', name)`, but a developer's query filters `name ILIKE '%mouse%'` and it is not used. Why?
Practice only: not graded, not saved, not evidence.

11. Apply it

Scale it up: generate a ten-million-row orders table (change the generate_series count), replay the four patterns, and record before-and-after EXPLAIN ANALYZE output for each. Measure the insert cost of every index you keep, as in step 6, and write one line per index: what it buys, what it costs. Drop any index whose query nobody runs; the final lab collects that evidence.

12. Review prompt

Without looking back: state the column-order rule for a composite index serving equality plus range plus sort. Explain when a partial index beats a full one, and what must be true of the query for the planner to use it. Name the two text-search index types from this lab and the query shape each serves. Finally, explain why BRIN was tiny and fast here, and when it would fail badly.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check