Databases · Advanced · 28 min
Index the clinic database for the queries it really runs
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7
You will add four indexes to the clinic booking database, each matched to one of part 3's queries or the new reminder job, reuse the double-booking constraint's index for free-slot search, remove an index that only costs writes, and end with a before and after timing table.
On this page
Part 3 left you with a clinic database that has real volume, five queries in ~/clinic-demo/queries.sql and their timings in ~/clinic-demo/timings-part3.txt. Some of those queries already have an index to lean on. Others read most of the appointments table to return a few dozen rows. This part works through them one at a time, using part 3's SQL exactly as you saved it.
The rule for the whole part is that every index has to earn its place. An index speeds up the reads it matches and slows down every write to the table, so you add an index only for a query you can name, check the plan uses it, and remove one that nothing reads. The EXPLAIN tutorial (/tutorials/speed-up-slow-postgres-queries-with-explain) covers reading plans; this part applies it and does not teach it again.
Everything here runs on PostgreSQL 18.7, the latest 18.x release, and the series stays on 18. PostgreSQL 19.0 was released on 19 November 2026; this part has not been checked against it. Your timings will differ from anyone else's, so you measure your own before and after rather than comparing with figures in the text.
Step 1 · Add the reminder query and take a fresh baseline
Part 3's file has the five queries the screens run. This part adds a sixth, and it is new here: the booking app is about to start texting patients the day before their visit (part 5 adds the column that records a reminder was sent). The job will run every 15 minutes and ask for booked appointments in the next 24 hours. Because it runs so often, it belongs in the measurements from the start.
Leave queries.sql as part 3 wrote it and make a part 4 copy with the reminder query on the end:
cd ~/clinic-demo
cat queries.sql - > queries-part4.sql <<'SQL'
\echo Q6 booked appointments in the next 24 hours for reminders
SELECT a.id, a.patient_id, a.starts_at
FROM appointments AS a
WHERE a.status = 'booked'
AND a.starts_at >= now()
AND a.starts_at < now() + interval '24 hours'
ORDER BY a.starts_at;
SQLTo read one query's plan at a time, split the file into one file per query. Each query in the file follows an \echo Q<n> ... line, so awk starts a new file at each label and skips psql's backslash commands:
cd ~/clinic-demo
mkdir -p part4
awk '/^\\echo Q/ { f = "part4/q" substr($2, 2) ".sql"; next } f && !/^\\/ { print > f }' queries-part4.sql
ls part4
cat part4/q3.sqlDefine a small shell function that runs one of them under EXPLAIN (ANALYZE, BUFFERS). It lasts as long as this terminal, so define it again if you open a new one:
explain() { { echo 'EXPLAIN (ANALYZE, BUFFERS)'; cat ~/clinic-demo/part4/"$1".sql; } | sudo -u postgres psql -d clinic -v ON_ERROR_STOP=1; }Now take the baseline the same way part 3 did: one run to warm the cache, a second run to keep. Take a fresh one rather than reusing timings-part3.txt: the queries use current_date and now(), so the rows they read have moved on since part 3, and part 3's file has no reminder timing. Part 3's numbers are still useful as a sanity check:
cd ~/clinic-demo
sudo -u postgres psql -d clinic < queries-part4.sql > /dev/null
sudo -u postgres psql -d clinic < queries-part4.sql > timings-part4-before.txt
grep -E '^(Q[1-6]|Time:)' timings-part4-before.txt
grep -E '^(Q[1-5]|Time:)' timings-part3.txtFinally, list the indexes the appointments table already has:
sudo -u postgres psql -d clinic -c '\di appointments*'Check it worked
ls part4 shows q1.sql to q6.sql, and q3.sql holds the patient history query, starting at SELECT and ending with ORDER BY a.starts_at DESC;. The new baseline has six labels, each followed by a Time: line. Q1 to Q5 should be in the same range as part 3's figures; if one differs by ten times or more, something else on the server changed and is worth finding before you go on. The index list shows appointments_pkey, appointments_public_id_key and appointments_no_double_booking, and nothing on patient_id or starts_at on its own. PostgreSQL indexes the referenced side of a foreign key (the primary key) but never the referencing column, so appointments.patient_id has no index even though it points at patients.
Step 2 · Let the constraint's GiST index find free slots
Part 2 added an exclusion constraint so a practitioner can never be double-booked. To enforce it, PostgreSQL built a GiST index on (practitioner_id, tstzrange(starts_at, ends_at)), and that index is just what the free-slot search (Q2) needs: one practitioner, appointments that overlap a time range. Look at it:
sudo -u postgres psql -d clinic -c '\d appointments' | grep -A1 -i 'exclude'You see something like "appointments_no_double_booking" EXCLUDE USING gist (practitioner_id WITH =, tstzrange(starts_at, ends_at) WITH &&) WHERE (status <> 'cancelled'). Now read the free-slot plan:
explain q2For each of next Monday's candidate slots, the plan probes appointments_no_double_booking with practitioner 42 and the slot's range. Four things line up for that to happen, and part 3 wrote the query so they do:
- The range expression in the query,
tstzrange(a.starts_at, a.ends_at), is the same expression as in the constraint. Writingtstzrange(a.starts_at, a.ends_at, '[)')would mean the same range but would not match the index. - The constraint is partial (
WHERE status <> 'cancelled'), so the query must saya.status <> 'cancelled'too. That is also the right business rule: a cancelled slot is free. btree_gist, which part 2 installed for the constraint, is what lets a GiST index hold the plainpractitioner_idcolumn alongside the range.- The candidate slots come from
generate_series(0, 47)with fixed bounds, so the planner expects a few dozen probes. Given agenerate_seriesover values from another table, it guesses 1,000 rows, and at that count reading the whole table once can look cheaper than probing the index.
If your constraint from part 2 has no WHERE clause, drop the status condition from q2.sql and queries-part4.sql instead.
Do not add an index for this query. The constraint's index already does the work, and every new booking would pay to update a second one.
Check it worked
The plan has an Index Scan (or a Bitmap Index Scan) on appointments_no_double_booking, and no Seq Scan on appointments. Q2 was already among the fastest in the baseline, and this is why.
Step 3 · Index the diary in the order the query reads it
Today's diary (Q1) asks for one clinic over one day. Part 3 put clinic_id on appointments for exactly this query, so the filter is an equality on a.clinic_id and a range on a.starts_at, both on the appointments table itself. The index to build is a multicolumn B-tree on those two columns.
A multicolumn B-tree is sorted by its first column, then by the second within each value of the first, so the column order decides how much of the index each lookup reads. Build it the wrong way round first, with the range column leading, so you can see the cost:
sudo -u postgres psql -d clinic -c "CREATE INDEX appointments_starts_clinic_idx ON appointments (starts_at, clinic_id);"
explain q1Building an index on 3 million rows takes a few seconds. The plan most likely uses appointments_starts_clinic_idx for the appointments side, either as an index scan or as a bitmap scan. Either way it reads today's entries for all 20 clinics to keep the one it needs. The index condition text names both columns, so it does not show the waste; the Buffers: shared hit=... figure on the appointments scan node and the number of rows it reads do. Note that buffers figure.
Now build it with the equality column first and drop the wrong one:
sudo -u postgres psql -d clinic -c "CREATE INDEX appointments_clinic_starts_idx ON appointments (clinic_id, starts_at);"
sudo -u postgres psql -d clinic -c "DROP INDEX appointments_starts_clinic_idx;"
explain q1With clinic_id first, each clinic's entries sit together, sorted by starts_at, so the scan jumps to clinic 1 at midnight and reads forward to the end of the day. It touches only the rows it returns. The plan still ends with a small Sort, because Q1 orders by practitioner name first, and sorting a few hundred rows costs next to nothing.
The general rule: columns compared with = first, then the one column used for a range. PostgreSQL 18 can sometimes use an index whose leading column the query does not mention, with a skip scan, but that is a fallback for low-cardinality leading columns, not a reason to get the order wrong.
This is the payoff for the copied column. Without appointments.clinic_id, the diary would have to find clinic 1's 15 practitioners first and probe an index on (practitioner_id, starts_at) once for each. Part 3's two-column foreign key keeps the copy in step with the practitioner's clinic, so the single range read is also a correct one.
Check it worked
The last plan names appointments_clinic_starts_idx on the appointments side, with an Index Cond something like (clinic_id = 1) AND (starts_at >= ...) AND (starts_at < ...). Its Buffers figure on that node is a fraction of the wrong-order one, and its execution time is a fraction of Q1's baseline. Q2's plan usually keeps the GiST index even with the new B-tree in place, because only the GiST index can test the range overlap; run explain q2 again to see which yours chose.
Step 4 · Build the patient history index without blocking bookings
Q3 finds a patient by email and lists their visits. The patient side is already indexed: part 2's patients_email_lower_key covers lower(email), which is exactly the expression Q3 uses, so the patient lookup is one index probe. The slow half is the appointments side, where patient_id, the foreign key column PostgreSQL did not index for you, has no index at all. Look at the plan before you fix it:
explain q3You see patients_email_lower_key used on patients, and something like a Seq Scan on appointments (possibly parallel) that reads every row to find this patient's two dozen or so visits.
Index (patient_id, starts_at). The second column lets the visits come out already in date order: B-tree indexes can be read backwards, so ORDER BY a.starts_at DESC does not need a DESC index.
A plain CREATE INDEX blocks every INSERT, UPDATE and DELETE on the table until it finishes. On a clinic that takes bookings all day, use CONCURRENTLY. It builds the index in two passes while writes continue, takes longer, and cannot run inside a transaction block (BEGIN ... COMMIT):
sudo -u postgres psql -d clinic -c "CREATE INDEX CONCURRENTLY appointments_patient_starts_idx ON appointments (patient_id, starts_at);"A concurrent build waits for transactions that were already open when it started, so a forgotten session sitting idle in transaction holds it up. On a large table you can watch the build from a second terminal:
SELECT phase, blocks_done, blocks_total, tuples_done, tuples_total
FROM pg_stat_progress_create_index;If a concurrent build fails part way (a deadlock, a cancelled command, a unique violation), it leaves an index marked INVALID behind. It is not used for reads but is still updated on every write. Check that every index on the table is valid:
sudo -u postgres psql -d clinic -c "SELECT indexrelid::regclass AS index, indisvalid FROM pg_index WHERE indrelid = 'appointments'::regclass;"If any row shows f, drop that index with DROP INDEX CONCURRENTLY <index name>; (replace the placeholder with the name from the list) and run the CREATE INDEX CONCURRENTLY again.
Then read the plan again:
explain q3Check it worked
Every row in the validity list shows t. The new plan is a nested loop: patients_email_lower_key finds the patient, then appointments_patient_starts_idx (often as an Index Scan Backward) returns their visits. The sequential scan on appointments is gone, and the time drops to around a millisecond or less.
Step 5 · Keep the reminder index small with a partial index
The reminder job (Q6) only ever reads booked appointments in the next day. In part 3's data, booked means a future appointment that has not been cancelled, about one row in nine. A partial index holds only the rows that match its WHERE clause:
sudo -u postgres psql -d clinic -c "CREATE INDEX CONCURRENTLY appointments_booked_starts_idx ON appointments (starts_at) WHERE status = 'booked';"You cannot write WHERE starts_at > now() in an index: the predicate must give the same answer forever, and now() changes. status = 'booked' works as a stand-in, as long as the app moves every appointment to completed, no_show or cancelled once it has happened, which is how part 3's data is shaped. Old rows then leave the index on their own.
For the planner to use a partial index, the query's WHERE clause must imply the index's predicate. Q6 says a.status = 'booked', which matches exactly. A query with status IN ('booked', 'cancelled') would not.
Compare the sizes of the indexes, then read the plan:
sudo -u postgres psql -d clinic -c "SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_stat_user_indexes WHERE relname = 'appointments' ORDER BY pg_relation_size(indexrelid) DESC;"
explain q6Small indexes matter most on small servers. If the clinic database runs on, say, a VPS with 2 GB of memory, a partial index like this can stay in memory all day, while a full index on starts_at would compete with the table for the same cache.
Check it worked
appointments_booked_starts_idx is several times smaller than appointments_clinic_starts_idx. The reminder plan uses it, and the time is a small fraction of Q6's baseline.
Step 6 · Answer the reports from the index alone with INCLUDE
The two reports read a date range and need a few columns from every row in it. Q4, the no-show rate, reads 90 days and needs clinic_id and status. Q5, revenue per service, reads 12 months and needs service_id, status and fee. An index on starts_at alone would find the rows, then visit the table for each one to read those columns, and part 3 inserted each practitioner's diary in turn, so rows for one day are spread across the whole table. INCLUDE stores extra columns in the index's leaf pages, without making them part of the sort key, so PostgreSQL can answer from the index alone:
sudo -u postgres psql -d clinic -c "CREATE INDEX CONCURRENTLY appointments_reporting_idx ON appointments (starts_at) INCLUDE (clinic_id, service_id, status, fee);"An index-only scan still checks the table's visibility map to know whether each row is visible to the query. Pages that changed since the last vacuum force a visit to the table, shown as Heap Fetches in the plan. Autovacuum keeps the map current on a running system; run a vacuum now so the new index starts in good shape, then read both report plans:
sudo -u postgres psql -d clinic -c "VACUUM (ANALYZE) appointments;"
explain q4
explain q5Q4 reads about an eighth of the table, and its plan has an Index Only Scan using appointments_reporting_idx feeding the join to clinics. Q5 is different: 12 months is about half the table. Reading half a narrow index is still usually cheaper than reading the whole table, but a parallel Seq Scan is a reasonable choice at that share too, and on some machines the planner takes it. Either plan is fine; the timing table at the end tells you whether the index helped.
INCLUDE makes the index bigger, so keep it for queries that run often or read many rows. Including fee also means every fee change writes a new index entry. That is cheap here because fees change rarely; for a column updated constantly, it would not be.
Check it worked
The Q4 plan has an Index Only Scan using appointments_reporting_idx with Heap Fetches: 0 or close to it, and its time is well below Q4's baseline. The Q5 plan uses either the same index or a sequential scan, as described above.
Step 7 · Find an index that costs writes and is never read
Indexes collect over the years, often added "because the column is in a WHERE clause". Add one of those so you can see how to catch it. status has four values, so an index on it alone rarely beats a scan or one of the indexes you just built:
sudo -u postgres psql -d clinic -c "CREATE INDEX CONCURRENTLY appointments_status_idx ON appointments (status);"Run all six queries again, the same way as the baseline. This also records the after timings for the last step:
cd ~/clinic-demo
sudo -u postgres psql -d clinic < queries-part4.sql > /dev/null
sudo -u postgres psql -d clinic < queries-part4.sql > timings-part4-after.txtNow ask PostgreSQL how often each index has been read:
sudo -u postgres psql -d clinic -c "SELECT indexrelname, idx_scan, last_idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_stat_user_indexes WHERE relname = 'appointments' ORDER BY idx_scan;"appointments_status_idx should show idx_scan of 0 and an empty last_idx_scan: none of the six queries chose it. appointments_pkey and appointments_public_id_key may also show few scans; keep them, because they enforce primary key and uniqueness rules, and the same goes for the exclusion constraint's index. On your own server, read these figures over weeks, not minutes: a report that runs once a month looks unused for 29 days. The counters are per server, so check read replicas separately, and they restart from zero when statistics are reset.
To see what the unused index costs, insert a day of bookings for every practitioner in 2030, inside a transaction you roll back. The WAL option reports how much write-ahead log the insert produced, which grows with every index the rows have to enter. The times are in Lagos time (+01), matching the database's time zone from part 3:
cd ~/clinic-demo
sudo -u postgres psql -d clinic -v ON_ERROR_STOP=1 > with-status-idx.txt <<'SQL'
BEGIN;
EXPLAIN (ANALYZE, WAL, COSTS OFF)
INSERT INTO appointments (clinic_id, practitioner_id, patient_id, service_id, starts_at, ends_at, status, fee)
SELECT p.clinic_id, p.id, 1 + (p.id * 7919) % 200000, s.id, slot, slot + interval '30 minutes', 'booked', s.fee
FROM practitioners AS p
JOIN services AS s ON s.clinic_id = p.clinic_id AND s.name = 'General consultation'
CROSS JOIN generate_series(timestamptz '2030-01-07 08:00+01', timestamptz '2030-01-07 15:30+01', interval '30 minutes') AS slot;
ROLLBACK;
SQL
grep -E 'WAL:|Execution Time' with-status-idx.txtEach practitioner gets their own clinic's 30-minute general consultation at its current fee, so each row is a valid booking that passes every constraint. Drop the index and run the same insert again:
cd ~/clinic-demo
sudo -u postgres psql -d clinic -c "DROP INDEX CONCURRENTLY appointments_status_idx;"
sudo -u postgres psql -d clinic -v ON_ERROR_STOP=1 > without-status-idx.txt <<'SQL'
BEGIN;
EXPLAIN (ANALYZE, WAL, COSTS OFF)
INSERT INTO appointments (clinic_id, practitioner_id, patient_id, service_id, starts_at, ends_at, status, fee)
SELECT p.clinic_id, p.id, 1 + (p.id * 7919) % 200000, s.id, slot, slot + interval '30 minutes', 'booked', s.fee
FROM practitioners AS p
JOIN services AS s ON s.clinic_id = p.clinic_id AND s.name = 'General consultation'
CROSS JOIN generate_series(timestamptz '2030-01-07 08:00+01', timestamptz '2030-01-07 15:30+01', interval '30 minutes') AS slot;
ROLLBACK;
SQL
grep -E 'WAL:|Execution Time' without-status-idx.txtCheck it worked
Both runs print a WAL: records=... bytes=... line. The second has fewer records and fewer bytes, because each of the 4,800 rows enters one index fewer. Every new booking, all day, saves that work, and so do your backups and replicas, which copy the WAL. \di appointments* no longer lists appointments_status_idx, and because both inserts were rolled back, there are no appointments in 2030.
Step 8 · Compare before and after
The after timings were taken with all the new indexes in place. Put them beside the baseline, one row per query, with the label, the time before and the time after in milliseconds:
cd ~/clinic-demo
paste <(grep -E '^Q[1-6] ' timings-part4-before.txt | cut -d' ' -f1) \
<(grep '^Time:' timings-part4-before.txt | cut -d' ' -f2) \
<(grep '^Time:' timings-part4-after.txt | cut -d' ' -f2)
rm -f with-status-idx.txt without-status-idx.txtKeep queries-part4.sql, both timing files and the part4 folder next to part 3's files. When someone asks in a year why appointments_reporting_idx exists, the answer is a query name and the two numbers beside it. Part 5's baseline migration captures these indexes along with the rest of the schema, so leave them in place.
Check it worked
The table has six rows. Q1 (diary), Q3 (patient history) and Q6 (reminders) usually show the largest gains, often tens or hundreds of times faster. Q4 improves because it now reads a slice of a narrow index instead of the whole table. Q5 improves less, or not at all if its plan kept the sequential scan, because it still reads half a year's worth of rows or more. Q2 stays about the same, because the constraint's index was already serving it.
Next steps
- Turn today's indexes into a migration you can run on every environment:
/tutorials/change-the-clinic-schema-safely-with-versioned-migrations. - Find the next slow query with
pg_stat_statementsand plan reading:/tutorials/speed-up-slow-postgres-queries-with-explain. - Keep index-only scans working by keeping the visibility map current:
/tutorials/keep-postgresql-healthy-with-vacuum-and-autovacuum. - Go back to the data and queries this part measured:
/tutorials/fill-the-clinic-database-with-realistic-test-data.
Related tutorials
- Use SQLite safely in a Python app: WAL mode, foreign keys and busy timeoutsYou will build a small room-booking store on SQLite with Python 3.15, reproduce the "database is locked" error with two writer processes, and end with a connection helper that turns on foreign keys, WAL mode, a busy timeout and BEGIN IMMEDIATE writes, plus a tested online backup.
- Throttle login attempts with a sliding window in RedisYou will protect a Python login function from password guessing with a sliding-window log in Redis sorted sets, checked atomically in a Lua script, with per-address lockouts that double each time, an account-wide rule that asks for an extra check instead of locking the owner out, and tests that replay 50 guesses.
- Run background jobs with Redis Streams and consumer groupsYou will build a small receipt-sending job queue on Redis 8 Streams with two Python workers that share the work, recover jobs from a crashed worker, park repeated failures in a dead-letter stream and never send the same receipt twice.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials