Index-Friendly Rewrites and Fresh Statistics
Rewrite predicates the index can actually serve, replace OFFSET paging with a keyset, trade 5,000 round trips for one statement, and watch stale statistics flip a plan.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: unwrap the predicates
- Step 2: page with a keyset, not with OFFSET
- Step 3: 5,000 statements into one
- Step 4: statistics decide the plan
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of Indexing & Query Optimization
- How a B-Tree Index Finds Your Rows Concept · 20 min
- Reading an Execution Plan Node by Node Worked example · 30 min
- Lab: Designing Indexes for a Workload, Text Search Included Lab · 30 min
- Index-Friendly Rewrites and Fresh Statistics Lab · 25 min
- Finding the Queries That Actually Matter Lab · 20 min
- Check: Diagnose Three Slow Queries Knowledge check · 8 questions
What you will learn
- Rewrite queries to be index-friendly (sargable predicates, keyset pagination, set-based instead of row-by-row access) and keep planner statistics current.
Prerequisites: SQL Fundamentals
01. Goal and setup
Sometimes the fastest index is useless because the query never asks for it in a language the index understands. A predicate wrapped in a function, a page fetched with OFFSET, a loop of single-row statements — each defeats the machinery the previous lab built. And sometimes the query is fine but the planner is working from an outdated map. This lab fixes both sides of that divide: rewrites that make queries sargable — searchable by index — and statistics that keep the planner honest.
You need: the qopt-lab container with the qopt database and its indexes from lessons 2 and 3, plus Python 3.12 or newer with sqlalchemy and psycopg (uv pip install "sqlalchemy==2.1.9" "psycopg[binary]==3.3.9"; tested with those versions on Python 3.12).
As in the previous lab, outputs that print timings are marked Illustrative output: they come from one run on a four-core desktop, so expect different absolutes and similar ratios. Every step also has an Expected output you can match exactly — row counts and plans printed without timings.
02. Step 1: unwrap the predicates
An index on created_at stores raw timestamps in sorted order. EXTRACT(YEAR FROM created_at) = 2026 asks the planner to compute something for every row and compare — no sorted starting point exists for that expression, so the index is out. Put the bare column on one side and constants on the other, and the half-open range >= 2026-01-01 AND < 2027-01-01 restores it:
EXPLAIN (ANALYZE)
SELECT count(*) FROM orders
WHERE EXTRACT(YEAR FROM created_at) = 2026;
EXPLAIN (ANALYZE)
SELECT count(*) FROM orders
WHERE created_at >= timestamptz '2026-01-01'
AND created_at < timestamptz '2027-01-01';-> Parallel Seq Scan on orders (cost=0.00..30755.00 rows=4167
width=0)
(actual time=0.033..195.334 rows=302197 loops=3)
Filter: (EXTRACT(year FROM created_at) = '2026'::numeric)
Rows Removed by Filter: 364470
Execution Time: 215.140 ms
-> Parallel Index Only Scan using orders_created_idx on orders
(cost=0.43..23009.83 rows=381335 width=0)
(actual time=0.079..48.777 rows=302197 loops=3)
Index Cond: (created_at >= ... AND created_at < ...)
Execution Time: 72.396 msTwo wins hide in that output. The range query runs three times faster on the index-only scan. And look at the estimates: the planner guessed 4,167 rows per process — about 10,000 in total, its generic 0.5% guess — where each of the three processes actually found about 302,000 (906,000 in total): off by a factor of about ninety. Compare per-loop with per-loop, or total with total, never one with the other; with max_parallel_workers_per_gather = 0 the same plan shows the total estimate, rows=10000, directly. A function-wrapped column has no histogram, so the planner falls back to that generic guess, which corrupts every join and memory decision above it. The rewrite fixes speed and honesty.
Arithmetic on the column is the same trap. A service query asked for orders that would still be inside a 30-day window: created_at + interval '30 days' > ... — addition on the indexed column. Algebra moves it across the comparison:
EXPLAIN (ANALYZE)
SELECT count(*) FROM orders
WHERE created_at + interval '30 days' > timestamptz '2026-10-24';
EXPLAIN (ANALYZE)
SELECT count(*) FROM orders
WHERE created_at > timestamptz '2026-10-24' - interval '30 days';-> Parallel Seq Scan on orders
Filter: ((created_at + '30 days'::interval) > ...)
Rows Removed by Filter: 628938
Execution Time: 155.088 ms
-> Index Only Scan using orders_created_idx on orders
Index Cond: (created_at > (... - '30 days'::interval))
Heap Fetches: 0
Execution Time: 21.222 ms155 ms to 21 ms. When you truly must filter on the computed value — lower(email) for case-insensitive login is the classic — keep the expression and index it, with an expression index: CREATE INDEX ON users (lower(email)). The rule is symmetry: the index stores whatever expression you declare, and only queries using that same expression can ride it. Casting styles such as CAST(created_at AS date) BETWEEN ... fall into the same bucket as EXTRACT — unwrap them into a range on the raw column. Before trusting any rewrite, prove that it returns the same rows as the original — one pass over the table counts all four predicates:
SELECT
count(*) FILTER (WHERE EXTRACT(YEAR FROM created_at) = 2026)
AS year_fn,
count(*) FILTER (WHERE created_at >= timestamptz '2026-01-01'
AND created_at < timestamptz '2027-01-01')
AS year_range,
count(*) FILTER (WHERE created_at + interval '30 days'
> timestamptz '2026-10-24') AS window_fn,
count(*) FILTER (WHERE created_at
> timestamptz '2026-10-24' - interval '30 days')
AS window_range
FROM orders; year_fn | year_range | window_fn | window_range
---------+------------+-----------+--------------
906591 | 906591 | 113186 | 113186
(1 row)03. Step 2: page with a keyset, not with OFFSET
LIMIT 20 OFFSET 799980 still reads and throws away 799,980 rows before returning page 40,000; the deeper the page, the more wasted work, and rows shift between pages whenever data changes. A keyset (or seek) pagination remembers where reading stopped and continues from that key: WHERE id > :last ORDER BY id LIMIT 20. Every page costs the same. Benchmark both at increasing depths:
import statistics, time
from sqlalchemy import create_engine, text
engine = create_engine(
"postgresql+psycopg://lab:lab@localhost:55461/qopt")
PAGE, DEPTHS = 20, [1, 500, 1000, 2000, 4000, 8000]
def median_ms(fn, repeats=3):
times = []
for _ in range(repeats):
t0 = time.perf_counter()
rows = fn()
times.append((time.perf_counter() - t0) * 1000)
assert len(rows) == PAGE
return statistics.median(times)
print("page (20 rows) | OFFSET (ms) | keyset (ms)")
with engine.connect() as conn:
for page in DEPTHS:
offset = (page - 1) * PAGE
def by_offset():
return conn.execute(text(
"SELECT id, customer_id, total FROM orders"
" ORDER BY id LIMIT :lim OFFSET :off"),
{"lim": PAGE, "off": offset}).fetchall()
def by_keyset(): # ids here have no gaps, so the last id
# of the previous page equals the offset
return conn.execute(text(
"SELECT id, customer_id, total FROM orders"
" WHERE id > :last ORDER BY id LIMIT :lim"),
{"last": offset, "lim": PAGE}).fetchall()
print(f"#{page:<14} | {median_ms(by_offset):10.1f}"
f" | {median_ms(by_keyset):10.1f}")page (20 rows) | OFFSET (ms) | keyset (ms)
#1 | 0.8 | 0.8
#500 | 2.2 | 0.7
#1000 | 5.0 | 0.7
#2000 | 8.8 | 0.7
#4000 | 12.7 | 0.8
#8000 | 23.4 | 1.1OFFSET grows linearly with depth; the keyset page costs the same everywhere. Both methods return the same page — check it for page 40,000:
SELECT id FROM orders ORDER BY id LIMIT 3 OFFSET 799980;
SELECT id FROM orders WHERE id > 799980 ORDER BY id LIMIT 3; id
--------
799981
799982
799983
(3 rows)
id
--------
799981
799982
799983
(3 rows)Two practical notes. First, this feed pages by id because the primary key is unique and monotonic; for a business order like newest first, order by (created_at DESC, id DESC) and continue from a cursor of both values — WHERE (created_at, id) < (:last_ts, :last_id) — because timestamps repeat and a cursor without a tie-breaker skips rows. Second, keyset pages have no page numbers, only next and previous, which is why APIs built this way (the API design lesson covers the shapes) expose cursor tokens rather than ?page=401.
04. Step 3: 5,000 statements into one
The same instinct that hides SQL inside loops hides the database inside the application. A nightly job archived 5,000 shipped orders by fetching their ids in Python and issuing one UPDATE per id. Each statement is a network round trip, a parse, a plan, and an index probe; the set-based form says it once. The script below builds a 200,000-row scratch copy, archive_test, so the real orders table is untouched, archives 5,000 shipped orders row by row, then the next 5,000 in one statement. Save it as 04-archive.py and run it with uv run python 04-archive.py:
import time
from sqlalchemy import create_engine, text
engine = create_engine(
"postgresql+psycopg://lab:lab@localhost:55461/qopt")
SETUP = [
"DROP TABLE IF EXISTS archive_test",
"CREATE TABLE archive_test AS"
" SELECT id, customer_id, status, total, created_at"
" FROM orders WHERE id <= 200000",
"ALTER TABLE archive_test ADD PRIMARY KEY (id)",
"ANALYZE archive_test",
]
SHIPPED = ("SELECT id FROM archive_test WHERE status = 'shipped'"
" ORDER BY id LIMIT 5000")
with engine.begin() as conn: # a fresh 200,000-row copy each run
for stmt in SETUP:
conn.execute(text(stmt))
with engine.begin() as conn:
ids = [r[0] for r in conn.execute(text(SHIPPED))]
t0 = time.perf_counter()
for oid in ids: # one round trip per row
conn.execute(text(
"UPDATE archive_test SET status = 'archived'"
" WHERE id = :i"), {"i": oid})
row_by_row = time.perf_counter() - t0
with engine.begin() as conn:
ids2 = [r[0] for r in conn.execute(text(SHIPPED))]
t0 = time.perf_counter()
conn.execute(text(
"UPDATE archive_test SET status = 'archived'"
" WHERE id = ANY(:ids)"), {"ids": ids2})
set_based = time.perf_counter() - t0
print(f"row-by-row : {row_by_row:6.2f} s ({len(ids):,} statements)")
print(f"set-based : {set_based:6.2f} s (1 statement)")row-by-row : 1.34 s (5,000 statements)
set-based : 0.07 s (1 statement)SELECT status, count(*) FROM archive_test GROUP BY status ORDER BY status; status | count
-----------+--------
archived | 10000
cancelled | 8928
completed | 150036
pending | 2991
shipped | 28045
(5 rows)Roughly twenty times faster on this run, from one idea: let the database treat the set as a set. The same shape applies to reads — the N+1 query problem you met in the SQLAlchemy lab is this bug wearing a different hat — and to writes via UPDATE ... FROM, WHERE id = ANY(...), or a single multi-row INSERT.
05. Step 4: statistics decide the plan
Everything the planner knows about your data beyond its DDL comes from ANALYZE: row counts, histograms, most common values, correlation with physical order. No statistics, no sound plan. Autovacuum normally keeps them fresh, but a bulk load into a fresh table outpaces it — so migrations and backfills end with an explicit ANALYZE, a habit the migrations skill builds. See what stale statistics do, with autovacuum switched off on a scratch table so the failure is deterministic: one million rows, 99% belonging to one big retail customer (id 7), indexed. TIMING OFF keeps the real row counts but drops the clock readings, and with no statistics yet the estimates are fixed defaults, so this output matches yours exactly:
DROP TABLE IF EXISTS staging_orders;
CREATE TABLE staging_orders (
id bigint GENERATED ALWAYS AS IDENTITY,
customer_id bigint NOT NULL,
total numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL
);
ALTER TABLE staging_orders SET (autovacuum_enabled = false);
SELECT setseed(0.42);
INSERT INTO staging_orders (customer_id, total, created_at)
SELECT CASE WHEN g % 100 = 0
THEN (random() * 49999)::int + 1 ELSE 7 END,
round((random() * 480 + 9.90)::numeric, 2),
timestamptz '2026-10-20' + (random() * 3) * interval '1 day'
FROM generate_series(1, 1000000) g;
CREATE INDEX staging_customer_idx
ON staging_orders (customer_id);
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM staging_orders WHERE customer_id = 7;NOTICE: table "staging_orders" does not exist, skipping
DROP TABLE
CREATE TABLE
ALTER TABLE
setseed
---------
(1 row)
INSERT 0 1000000
CREATE INDEX
Aggregate (cost=7085.88..7085.89 rows=1 width=8) (actual rows=1 loops=1)
-> Bitmap Heap Scan on staging_orders
(cost=59.17..7073.38 rows=5000 width=0) (actual rows=990000 loops=1)
Recheck Cond: (customer_id = 7)
Heap Blocks: exact=7353
-> Bitmap Index Scan on staging_customer_idx
(cost=0.00..57.92 rows=5000 width=0) (actual rows=990000 loops=1)
Index Cond: (customer_id = 7)The planner guessed 5,000 rows — the default selectivity guess for an equality with no statistics — and built a bitmap plan for a small result. Then 990,000 rows actually came out of the index, and the heap scan visited all 7,353 pages of the table to count them. Collect the statistics and ask again:
ANALYZE staging_orders;
EXPLAIN (ANALYZE)
SELECT count(*) FROM staging_orders WHERE customer_id = 7;
SELECT most_common_vals, most_common_freqs, n_distinct
FROM pg_stats
WHERE tablename = 'staging_orders' AND attname = 'customer_id';-> Parallel Seq Scan on staging_orders
(cost=0.00..12561.33 rows=412889 width=0)
(actual time=0.017..33.885 rows=330000 loops=3)
Filter: (customer_id = 7)
Rows Removed by Filter: 3333
Execution Time: 68.973 ms
most_common_vals | most_common_freqs | n_distinct
------------------+-------------------+------------
{7} | {0.99093336} | 275The plan flipped to a parallel sequential scan, and the query ran about twice as fast on this machine (compare with your own EXPLAIN (ANALYZE) of both versions). pg_stats shows why the planner is now right: ANALYZE learned that customer 7 alone is about 99% of the table (most_common_freqs; the exact figure comes from a random sample of rows, so yours will differ slightly), so an index detour would only add work. Note the symmetry with the first lesson: a correct plan refused the index. When a heavily skewed column needs finer histograms, raise its target (ALTER TABLE ... ALTER COLUMN ... SET STATISTICS 500) and re-ANALYZE; when the skew spans several columns together, CREATE STATISTICS collects what single-column histograms cannot.
06. Troubleshooting
07. Check your understanding
08. Apply it
Take the slow statements you found in your own project (or ask its ORM to log SQL for a day). For each, apply this lab's checklist in order: unwrap function-wrapped predicates, replace deep OFFSET with a keyset, collapse statement loops into one set operation, and confirm ANALYZE runs after every bulk load. Keep a before-and-after EXPLAIN ANALYZE pair per statement — that evidence is what the final lab turns into a systematic loop.
09. Review prompt
Without looking back: define sargable in one sentence and give two rewrites that make a predicate sargable. Explain why OFFSET paging degrades with depth and what a keyset cursor must contain to be safe. Then describe what ANALYZE collects, what happens to plans when it is missing after a bulk load, and two ways to improve estimates on skewed data.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.