Databases · Intermediate · 24 min
Fill the clinic database with realistic test data using generate_series
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7
You will load 20 clinics, 300 practitioners, 200,000 patients and about 3 million appointments into the clinic database with repeatable SQL that passes every constraint, then time the five queries the booking app really runs.
On this page
A database with ten hand-typed rows tells you nothing about speed. Every query is fast when the table fits in one page. Before you add indexes in the next part, the clinic database needs the volume and shape of a real booking system: two years of appointments, busy and quiet clinics, patients who visit often and patients who came once.
In this part you generate that data inside PostgreSQL with generate_series, random() and INSERT ... SELECT. Nothing is downloaded, so it costs no bandwidth, which matters if your server sits behind metered or prepaid data. The data still has to pass every rule from part 2, including the one that stops a practitioner being double-booked, so you generate appointments on each clinic's own slot grid rather than at random times.
You finish with the five queries the app runs every day and a file of their current timings, which part 4 uses as its baseline.
The tutorial starts from the schema part 2 leaves in the clinic database, with every table empty. That schema has seven tables: clinics (each with a name, a city, a country, a timezone and a currency), practitioners (each belongs to one clinic, with a case-insensitive unique email), patients (with a case-insensitive unique email and at least an email or a phone), services (each belongs to one clinic, with a duration and a fee in that clinic's currency), practitioner_services (which services each practitioner offers), opening_hours (one row per clinic and ISO weekday) and appointments (practitioner, patient, service, starts_at, ends_at, status, the agreed fee, notes and created_at). Step 3 adds a clinic_id column to appointments and makes its fee required. The commands use PostgreSQL 18. PostgreSQL 19 was released in November 2026, and everything here works the same on it.
Step 1 · Work in the part 1 folder and set the session time zone
Keep the generator scripts in ~/clinic-demo, next to the schema.sql and schema-after-part-2.sql from parts 1 and 2. If you are starting here on another machine, create the folder:
mkdir -p ~/clinic-demo
cd ~/clinic-demoEach clinic already carries its own zone in clinics.timezone, from part 1. The generator below uses it: it builds each day's slots from opening hours such as 08:00 in clinic time, then converts them with AT TIME ZONE c.timezone, so the stored timestamptz is the right moment wherever the clinic is. The fictional Larkfield clinics in this part are all in Nigeria, so every generated clinic is Africa/Lagos, which is West Africa Time all year with no daylight saving.
Two things still depend on the session's own time zone rather than the clinic's: what current_date means, and how a timestamptz is shown. Set the database default to the same zone, so "today" in the generator and the queries matches the clinics' clock:
sudo -u postgres psql -d clinic -c "ALTER DATABASE clinic SET timezone TO 'Africa/Lagos';"If you add a clinic in Nairobi later, the generated slots stay correct because they follow each clinic's timezone; only the display default would then suit one city better than the other.
Check it worked
sudo -u postgres psql -d clinic -Atc "SHOW timezone;"A new session prints Africa/Lagos. The setting does not change sessions that were already open, so reconnect any psql window you have running.
Step 2 · Clear the tables and load the reference data
The generator starts from empty tables, so every run begins from the same place. The next script deletes every row in the seven clinic tables, including any rows left from parts 1 and 2, and resets the identity counters to 1. The schema and constraints stay. Do not run it on a database that holds real bookings.
If TRUNCATE fails with an error naming another table, you have added a table that references one of these. Add its name to the TRUNCATE list.
The reference data is small and written out in full: 20 clinics in ten Nigerian cities, all with timezone set to Africa/Lagos, country NG and currency NGN; opening hours for every day of the week (08:00 to 17:00 on weekdays, 09:00 to 13:00 at weekends); and the same 12 services at every clinic, each of which fits in a 30-minute slot. Services belong to a clinic in part 2's schema, so that is 240 service rows, 12 per clinic. Fees are in naira.
cat > ~/clinic-demo/01-reference.sql <<'SQL'
\set ON_ERROR_STOP on
BEGIN;
TRUNCATE appointments, practitioner_services, opening_hours, services,
practitioners, patients, clinics
RESTART IDENTITY;
INSERT INTO clinics (name, city, country, timezone, currency)
SELECT 'Larkfield ' || city || ' ' || (ARRAY['Central', 'North'])[branch],
city,
'NG',
'Africa/Lagos',
'NGN'
FROM unnest(ARRAY['Abeokuta', 'Abuja', 'Benin City', 'Enugu', 'Ibadan',
'Jos', 'Kaduna', 'Kano', 'Lagos', 'Port Harcourt']) AS c(city)
CROSS JOIN generate_series(1, 2) AS b(branch)
ORDER BY city, branch;
INSERT INTO opening_hours (clinic_id, weekday, opens, closes)
SELECT c.id,
wd,
CASE WHEN wd <= 5 THEN time '08:00' ELSE time '09:00' END,
CASE WHEN wd <= 5 THEN time '17:00' ELSE time '13:00' END
FROM clinics AS c
CROSS JOIN generate_series(1, 7) AS wd
ORDER BY c.id, wd;
INSERT INTO services (clinic_id, name, duration_minutes, fee)
SELECT c.id, s.name, s.duration_minutes, s.fee
FROM clinics AS c
CROSS JOIN (VALUES
(1, 'General consultation', 30, 15000.00),
(2, 'Follow-up visit', 15, 8000.00),
(3, 'Child health check', 30, 12000.00),
(4, 'Antenatal check', 30, 14000.00),
(5, 'Vaccination', 15, 6000.00),
(6, 'Blood test', 15, 9000.00),
(7, 'Malaria test', 15, 4500.00),
(8, 'Blood pressure review', 15, 5000.00),
(9, 'Dental check-up', 30, 18000.00),
(10, 'Eye test', 30, 16000.00),
(11, 'Physiotherapy session', 30, 20000.00),
(12, 'Prescription review', 15, 5500.00)
) AS s(position, name, duration_minutes, fee)
ORDER BY c.id, s.position;
COMMIT;
SQL
sudo -u postgres psql -d clinic < ~/clinic-demo/01-reference.sqlThe script is read through < rather than -f because the postgres user cannot read files in your home folder. The shell opens the file as you and hands it to psql. \set ON_ERROR_STOP on makes psql stop at the first error, and because everything runs inside BEGIN and COMMIT, a failure leaves the tables as they were.
Check it worked
sudo -u postgres psql -d clinic -c "SELECT (SELECT count(*) FROM clinics) AS clinics, (SELECT count(*) FROM opening_hours) AS opening_hours, (SELECT count(*) FROM services) AS services, (SELECT count(DISTINCT name) FROM services) AS service_names;"The result is one row: 20 clinics, 140 opening-hours rows (20 clinics times 7 days), 240 services and 12 distinct service names. The first clinic, Larkfield Abeokuta Central, has id 1, which confirms the identity counter was reset.
Step 3 · Record the clinic and require the fee on each appointment
Part 2's appointments table reaches the clinic only through the practitioner, and the fee column part 1 gave it for the price agreed at booking is still optional. Both matter once the table is large:
- A service's fee will change next year. Revenue reports must add up what each patient was actually charged, so every appointment must carry the fee copied from the service when it was booked, and a missing one is a bug.
- The reception diary and the clinic reports filter by clinic. With
clinic_idon the appointment, those queries need no join throughpractitioners, and part 4 can index it.
A copied clinic_id could drift from the practitioner's clinic. A two-column foreign key stops that: the pair (practitioner_id, clinic_id) must exist in practitioners. A foreign key can only point at columns covered by a unique constraint, so practitioners first gets UNIQUE (id, clinic_id). It is redundant as a rule, because id is already unique, but it gives the foreign key something to reference.
This is a one-off schema change, so it goes in its own file. The new clinic_id column is NOT NULL with no default, which works only while appointments is empty, as it is now; the same goes for making fee required without filling it first.
cat > ~/clinic-demo/schema-part-3.sql <<'SQL'
\set ON_ERROR_STOP on
BEGIN;
ALTER TABLE practitioners
ADD CONSTRAINT practitioners_id_clinic_key UNIQUE (id, clinic_id);
ALTER TABLE appointments
ADD COLUMN clinic_id bigint NOT NULL,
ALTER COLUMN fee SET NOT NULL,
ADD CONSTRAINT appointments_clinic_fk FOREIGN KEY (clinic_id)
REFERENCES clinics (id) ON DELETE RESTRICT,
ADD CONSTRAINT appointments_practitioner_clinic_fk FOREIGN KEY (practitioner_id, clinic_id)
REFERENCES practitioners (id, clinic_id) ON DELETE RESTRICT,
ADD CONSTRAINT appointments_fee_not_negative CHECK (fee >= 0);
COMMIT;
SQL
sudo -u postgres psql -d clinic < ~/clinic-demo/schema-part-3.sqlIf psql reports that a column of appointments contains null values, the table still has rows: run 01-reference.sql again first. If it reports that the column or a constraint already exists, you have run this file before and can skip it.
Check it worked
sudo -u postgres psql -d clinic -c '\d appointments'The column list now ends with clinic_id, and both clinic_id and fee are not null. Under the foreign-key constraints you see appointments_clinic_fk and appointments_practitioner_clinic_fk, and under the check constraints appointments_fee_not_negative.
Step 4 · Generate practitioners and patients from name lists
People need names that look like people, in the languages your users really have. A temporary table holds two short lists, given names and family names, and each generated person picks one of each at random. The lists mix Yoruba, Igbo, Hausa and other names from across Africa and beyond, and a few carry tone marks (Adébáyọ̀, Ọlátúnjí) so your app's text handling gets tested with characters outside plain ASCII.
setseed(0.43) fixes the starting point of random() for this session, so running the script again after 01-reference.sql produces the same names. Each practitioner is assigned to a clinic in turn, 15 per clinic, with a unique work address. Each practitioner then offers all 12 services of their own clinic in practitioner_services. A real dentist does not run antenatal checks; narrowing each practitioner to their specialty is a good exercise once the rest works.
Patients get addresses at example.org, a domain reserved for documentation, so a test email can never reach a real person. Every tenth address is written in mixed case (Patient4240@Example.org), which exercises the case-insensitive unique index from part 2. About one patient in seven has no email at all, only a phone number, like the patients who book by phone or WhatsApp in part 2; the patients_has_contact rule accepts them because the phone is there. Phone numbers follow the Nigerian mobile format.
cat > ~/clinic-demo/02-people.sql <<'SQL'
\set ON_ERROR_STOP on
SELECT setseed(0.43);
BEGIN;
CREATE TEMPORARY TABLE name_parts ON COMMIT DROP AS
SELECT ARRAY['Adaeze', 'Chinedu', 'Ngozi', 'Tunde', 'Aisha', 'Ibrahim', 'Funmilayo',
'Emeka', 'Zainab', 'Oluwaseun', 'Amina', 'Kelechi', 'Yetunde', 'Musa',
'Chiamaka', 'Babajide', 'Halima', 'Ifeoma', 'Segun', 'Fatima', 'Kwame',
'Wanjiru', 'Thandiwe', 'Amara', 'Maria', 'James', 'Priya', 'Wei',
'Adébáyọ̀', 'Ọlátúnjí'] AS given,
ARRAY['Okafor', 'Adeyemi', 'Bello', 'Eze', 'Okonkwo', 'Abubakar', 'Ogunleye',
'Nwosu', 'Danjuma', 'Adebayo', 'Ibekwe', 'Lawal', 'Mensah', 'Mwangi',
'Nkosi', 'Usman', 'Obi', 'Balogun', 'Yusuf', 'Chukwu', 'Ìdòwú', 'Àjàyí',
'Smith', 'Silva'] AS family;
INSERT INTO practitioners (clinic_id, full_name, email)
SELECT 1 + (g - 1) % 20,
'Dr ' || n.given[1 + floor(random() * cardinality(n.given))::int]
|| ' ' || n.family[1 + floor(random() * cardinality(n.family))::int],
'practitioner' || g || '@example.org'
FROM generate_series(1, 300) AS g
CROSS JOIN name_parts AS n
ORDER BY g;
INSERT INTO practitioner_services (practitioner_id, service_id)
SELECT p.id, s.id
FROM practitioners AS p
JOIN services AS s ON s.clinic_id = p.clinic_id;
INSERT INTO patients (full_name, email, phone, date_of_birth)
SELECT n.given[1 + floor(random() * cardinality(n.given))::int]
|| ' ' || n.family[1 + floor(random() * cardinality(n.family))::int],
CASE WHEN g % 7 = 3 THEN NULL
WHEN g % 10 = 0 THEN 'Patient' || g || '@Example.org'
ELSE 'patient' || g || '@example.org' END,
'+234' || (ARRAY['70', '80', '81', '90', '91'])[1 + floor(random() * 5)::int]
|| lpad(floor(random() * 100000000)::int::text, 8, '0'),
date '1940-01-01' + floor(random() * 30000)::int
FROM generate_series(1, 200000) AS g
CROSS JOIN name_parts AS n
ORDER BY g;
COMMIT;
SQL
sudo -u postgres psql -d clinic < ~/clinic-demo/02-people.sqlrandom() returns a value from 0 up to but not including 1, so 1 + floor(random() * n) is always a valid array position from 1 to n. Because random() is volatile, PostgreSQL calls it again for every row, which is what gives each patient a different name.
Check it worked
sudo -u postgres psql -d clinic -c "SELECT id, full_name, email, phone, date_of_birth FROM patients ORDER BY id LIMIT 5;"
sudo -u postgres psql -d clinic -c "SELECT count(*) AS patients, count(email) AS with_email, count(DISTINCT lower(email)) AS distinct_emails FROM patients;"
sudo -u postgres psql -d clinic -c "SELECT count(*) AS practitioners, (SELECT count(*) FROM practitioner_services) AS offered FROM practitioners;"The first query shows five plausible patients with different names, +234 phone numbers and birth dates between 1940 and 2022; patient 3 has an empty email. The second shows 200,000 patients, 171,428 of them with an email and 171,428 distinct emails. The third shows 300 practitioners and 3,600 practitioner-service links (300 times 12). Run 01-reference.sql and then 02-people.sql again and the first five patients come back identical, because the seed is fixed and this script reads no other table to choose them.
Step 5 · Generate two years of appointments on the slot grid
Random start times would break the no-double-booking rule within seconds. Real clinics book into fixed slots, so the script does the same. For every practitioner and every day in a 730-day window (21 months back and 3 months ahead), it joins that clinic's opening hours for the weekday and cuts them into 30-minute slots with generate_series. The slots are built as clinic wall-clock times, d.on_day + oh.opens, and AT TIME ZONE c.timezone turns each one into the absolute moment it is in that clinic. Every service lasts 15 or 30 minutes and starts at the beginning of its slot, so no two appointments for one practitioner can overlap.
Each slot then draws a few random numbers:
filldecides whether the slot is booked at all. About 90 per cent are.outcomedecides the status. About 6 per cent are cancelled. Past appointments are otherwise completed or missed, and the no-show rate varies by clinic from about 4 to 11 per cent, so the reporting query in a later step has something to find. Future appointments arebooked.service_numberpicks one of the 12 services. Theclinic_serviceslist numbers each clinic's own services 1 to 12, so the appointment always gets a service from the practitioner's clinic, one thatpractitioner_servicessays they offer.patient_idusespower(random(), 1.3), which skews towards low ids. Some patients come back often and many come rarely, as in a real practice.lead_dayssets when the booking was made, up to 30 days before the visit and never in the future.
Each appointment gets the clinic of its practitioner and the fee of its service at the time of booking, the two columns from the last step.
The WITH ... AS MATERIALIZED clause makes PostgreSQL compute each slot's random numbers once, store them, and let the insert read the stored rows. PostgreSQL already avoids folding a WITH query that calls a volatile function such as random() into the main query, but writing MATERIALIZED makes that intent explicit for the next person who edits the script.
cat > ~/clinic-demo/03-appointments.sql <<'SQL'
\set ON_ERROR_STOP on
SELECT setseed(0.44);
WITH slots AS MATERIALIZED (
SELECT p.id AS practitioner_id,
p.clinic_id,
g.slot AT TIME ZONE c.timezone AS starts_at,
random() AS fill,
random() AS outcome,
1 + floor(random() * 12)::int AS service_number,
1 + floor(power(random(), 1.3) * 200000)::int AS patient_id,
floor(random() * 31)::int AS lead_days
FROM practitioners AS p
JOIN clinics AS c ON c.id = p.clinic_id
CROSS JOIN generate_series(0, 729) AS n(day_number)
CROSS JOIN LATERAL (SELECT current_date - 640 + n.day_number AS on_day) AS d
JOIN opening_hours AS oh
ON oh.clinic_id = p.clinic_id
AND oh.weekday = extract(isodow FROM d.on_day)
CROSS JOIN LATERAL generate_series(d.on_day + oh.opens,
d.on_day + oh.closes - interval '30 minutes',
interval '30 minutes') AS g(slot)
),
clinic_services AS (
SELECT id, clinic_id, duration_minutes, fee,
row_number() OVER (PARTITION BY clinic_id ORDER BY id) AS service_number
FROM services
)
INSERT INTO appointments
(clinic_id, practitioner_id, patient_id, service_id,
starts_at, ends_at, status, fee, created_at)
SELECT s.clinic_id,
s.practitioner_id,
s.patient_id,
sv.id,
s.starts_at,
s.starts_at + make_interval(mins => sv.duration_minutes),
CASE
WHEN s.outcome < 0.06 THEN 'cancelled'
WHEN s.starts_at > now() THEN 'booked'
WHEN s.outcome < 0.10 + 0.01 * (s.clinic_id % 7) THEN 'no_show'
ELSE 'completed'
END,
sv.fee,
least(now(), s.starts_at - make_interval(days => s.lead_days))
FROM slots AS s
JOIN clinic_services AS sv
ON sv.clinic_id = s.clinic_id
AND sv.service_number = s.service_number
WHERE s.fill < 0.9
ORDER BY s.practitioner_id, s.starts_at;
ANALYZE;
SQL
time sudo -u postgres psql -d clinic < ~/clinic-demo/03-appointments.sqlExpect this to take several minutes. Most of the time goes on checking each row against the constraints: five foreign keys, the checks and the exclusion constraint's GiST index. That is the point: if any one of the roughly 3 million rows broke a rule, the whole INSERT would fail and nothing would be written. The ORDER BY inserts each practitioner's diary in time order, so each new row's index insertions land next to the previous row's and stay in memory. ANALYZE at the end refreshes the planner's statistics, so the timings in the last step reflect the full tables.
The seed fixes the sequence of random numbers, but which slot receives which number depends on the order PostgreSQL produces the slot rows in, and that follows the query plan. A second run on the same day gives the same appointments only while the plan stays the same; the ANALYZE at the end of the first run, or a different PostgreSQL version, can change it. The counts and the shape stay the same either way, which is what the timings need.
Check it worked
Count the appointments by status:
sudo -u postgres psql -d clinic -c "SELECT status, count(*), round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct FROM appointments GROUP BY status ORDER BY status;"The four statuses add up to about 3 million rows. completed is the large majority, booked is around 11 per cent (the three future months), cancelled is about 6 per cent and no_show is a few per cent. The exact counts move slightly from day to day because the window follows current_date.
Then confirm that every constraint on the tables is still marked valid, and see how much space the appointments take:
sudo -u postgres psql -d clinic -c "SELECT count(*) AS invalid_constraints FROM pg_constraint WHERE connamespace = 'public'::regnamespace AND NOT convalidated;"
sudo -u postgres psql -d clinic -c "SELECT pg_size_pretty(pg_total_relation_size('appointments')) AS appointments_size;"invalid_constraints is 0. The appointments table with its indexes is several hundred megabytes.
Step 6 · Prove the double-booking rule still holds
The load succeeding is already proof, but it is worth seeing the rule reject a clash on the full table. Try to book a second patient into a slot that is already taken:
sudo -u postgres psql -d clinic <<'SQL'
INSERT INTO appointments
(clinic_id, practitioner_id, patient_id, service_id, starts_at, ends_at, status, fee)
SELECT clinic_id, practitioner_id, 1, service_id, starts_at, ends_at, 'booked', fee
FROM appointments
WHERE status = 'booked'
ORDER BY id
LIMIT 1;
SQLCheck it worked
psql prints an error like conflicting key value violates exclusion constraint "appointments_no_double_booking", and no row is added. Because this script does not set ON_ERROR_STOP, psql reports the error and carries on, so your shell stays open.
Step 7 · Write the five queries the app runs
These are the queries behind the screens from the booking app: the reception desk's diary for today, the free slots shown when a patient books, a patient's history, and two reports for the clinic manager. Save them in one file so part 4 can run exactly the same SQL after adding indexes. Each query is preceded by an \echo label, and \timing on makes psql print how long each one took.
cat > ~/clinic-demo/queries.sql <<'SQL'
\set ON_ERROR_STOP on
\timing on
\echo Q1 todays diary for clinic 1
SELECT (a.starts_at AT TIME ZONE c.timezone)::time AS at,
pr.full_name AS practitioner, pt.full_name AS patient,
sv.name AS service, a.status
FROM appointments AS a
JOIN clinics AS c ON c.id = a.clinic_id
JOIN practitioners AS pr ON pr.id = a.practitioner_id
JOIN patients AS pt ON pt.id = a.patient_id
JOIN services AS sv ON sv.id = a.service_id
WHERE a.clinic_id = 1
AND a.starts_at >= current_date
AND a.starts_at < current_date + 1
AND a.status <> 'cancelled'
ORDER BY pr.full_name, a.starts_at;
\echo Q2 free slots for practitioner 42 next Monday
SELECT g.slot::time AS free_at
FROM practitioners AS p
JOIN clinics AS c ON c.id = p.clinic_id
JOIN opening_hours AS oh ON oh.clinic_id = p.clinic_id AND oh.weekday = 1
CROSS JOIN LATERAL (SELECT date_trunc('week', current_date)::date + 7 AS on_day) AS d
CROSS JOIN generate_series(0, 47) AS h(half_hour)
CROSS JOIN LATERAL (SELECT d.on_day + h.half_hour * interval '30 minutes' AS slot) AS g
WHERE p.id = 42
AND g.slot >= d.on_day + oh.opens
AND g.slot + interval '30 minutes' <= d.on_day + oh.closes
AND NOT EXISTS (
SELECT 1
FROM appointments AS a
WHERE a.practitioner_id = p.id
AND a.status <> 'cancelled'
AND tstzrange(a.starts_at, a.ends_at)
&& tstzrange(g.slot AT TIME ZONE c.timezone,
(g.slot + interval '30 minutes') AT TIME ZONE c.timezone))
ORDER BY g.slot;
\echo Q3 history for the patient with email patient4240@example.org
SELECT a.starts_at, sv.name AS service, pr.full_name AS practitioner, a.status, a.fee
FROM patients AS pt
JOIN appointments AS a ON a.patient_id = pt.id
JOIN services AS sv ON sv.id = a.service_id
JOIN practitioners AS pr ON pr.id = a.practitioner_id
WHERE lower(pt.email) = lower('patient4240@example.org')
ORDER BY a.starts_at DESC;
\echo Q4 no-show rate per clinic over the last 90 days
SELECT c.name AS clinic,
count(*) FILTER (WHERE a.status = 'no_show') AS no_shows,
count(*) FILTER (WHERE a.status IN ('completed', 'no_show')) AS due,
round(100.0 * count(*) FILTER (WHERE a.status = 'no_show')
/ nullif(count(*) FILTER (WHERE a.status IN ('completed', 'no_show')), 0), 1)
AS no_show_pct
FROM appointments AS a
JOIN clinics AS c ON c.id = a.clinic_id
WHERE a.starts_at >= current_date - 90
AND a.starts_at < now()
GROUP BY c.name
ORDER BY no_show_pct DESC;
\echo Q5 revenue per service over the last 12 months
SELECT sv.name AS service, count(*) AS completed, sum(a.fee) AS revenue
FROM appointments AS a
JOIN services AS sv ON sv.id = a.service_id
WHERE a.status = 'completed'
AND a.starts_at >= now() - interval '12 months'
GROUP BY sv.name
ORDER BY revenue DESC;
SQLA few details carry over from the earlier steps. Q1 and Q4 filter and group on the appointment's own clinic_id, so neither needs a join through practitioners to find the clinic. Q2 lists the day's 48 half-hour marks, keeps those inside the clinic's opening hours in clinic time, and keeps those that no live appointment overlaps, using the same range test as the exclusion constraint. Counting from a fixed 0 to 47, rather than calling generate_series on the opening times as the generator did, lets the planner know there are only a few dozen candidate slots, which matters for the plan part 4 reads. Q3 matches on lower(email), the expression the unique index from part 2 covers, and finds patient 4240 even though the address is stored as Patient4240@Example.org. Q4 counts only appointments that were due, so cancellations do not dilute the rate. Q5 adds up the fee charged on each appointment and groups by service name, so the same service at 20 clinics is one row.
Check it worked
Run the file once and look at the two report queries:
sudo -u postgres psql -d clinic < ~/clinic-demo/queries.sql | sed -n '/^Q4/,$p'Q4 lists all 20 clinics, with no-show rates spread from about 4 per cent to about 11 per cent, the pattern the generator built in. Q5 lists 12 services, with the 30-minute, higher-fee services such as physiotherapy and dental check-ups near the top. If both reports look right, the data has the shape you intended.
Step 8 · Record the baseline timings for part 4
The first run of a query reads pages from disk; later runs find them in memory. Run the file once to warm the cache, then again to keep the timings:
cd ~/clinic-demo
sudo -u postgres psql -d clinic < queries.sql > /dev/null
sudo -u postgres psql -d clinic < queries.sql > timings-part3.txt
grep -E '^(Q[1-5]|Time:)' timings-part3.txtThe output pairs each label with a Time: line in milliseconds. Your numbers depend on your hardware and on what else the server is doing, so compare them only with later runs on the same machine. Expect a wide spread: the free-slot query takes a few milliseconds at most, while the two reports read most of the appointments table and take hundreds of milliseconds or more.
A query that filters on one practitioner can already be fairly quick, because the exclusion constraint's GiST index covers practitioner_id and the time range. Others have no index to use and read most of the appointments table on every call. Part 4 shows which is which with EXPLAIN and fixes the slow ones.
Keep timings-part3.txt, queries.sql and the data in ~/clinic-demo and the clinic database. Part 4 starts from all three. To rebuild the data from scratch later, run 01-reference.sql, 02-people.sql and 03-appointments.sql again in that order; schema-part-3.sql is a one-off and does not need running again.
Check it worked
grep -c '^Time:' ~/clinic-demo/timings-part3.txtThe count is 5, one timing for each query. Open the file and note the five times in your own notes, next to the date and the server you ran them on, so part 4's comparison is like for like.
Next steps
- Make the slow queries fast in part 4: /tutorials/index-the-clinic-database-for-the-queries-it-really-runs.
- Go back over the rules this data had to pass: /tutorials/enforce-the-clinic-booking-rules-with-postgresql-constraints.
- Learn to read the plans behind your timings: /tutorials/speed-up-slow-postgres-queries-with-explain.
- Load data from files instead of generating it: /tutorials/load-and-export-csv-data-with-postgresql-copy.
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