Databases · Intermediate · 24 min
Enforce the clinic booking rules with PostgreSQL constraints
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7
You will move the clinic booking rules into PostgreSQL 18 as named NOT NULL, CHECK, unique, foreign key and exclusion constraints, and prove each one with an INSERT or DELETE that the database refuses.
On this page
Part 1 gave the clinic booking app its tables and keys. Those tables still accept nonsense. An appointment can end before it starts, a service can cost minus 500, two patients can share one email address in different capitals, and one doctor can be booked for two patients at 09:15 on the same morning. The app is supposed to stop all of that, but an app has bugs, an admin script skips the app, and two booking requests that arrive in the same second can both see the slot as free.
In this part you move those rules into the database, where every client has to obey them. You start by proving the gap: four bad rows that PostgreSQL accepts without complaint. Then you add the rules one kind at a time, and prove each one with a statement that PostgreSQL now refuses. Every constraint gets a name, so the error tells you, and later the app, exactly which rule was broken.
The running example is the database behind the clinic booking app from the design series: clinics, practitioners, patients, services, opening hours and appointments. The commands use PostgreSQL 18. PostgreSQL 19 came out in November 2026, and everything here works the same on it.
Step 1 · Load the part 1 schema and see what it lets through
Work in the folder from part 1, or create it now:
mkdir -p ~/clinic-demo
cd ~/clinic-demoThis is the schema part 1 ends with, unchanged. Every table has a primary key, the public-facing tables have a public_id generated by PostgreSQL 18's uuidv7(), and the relationships are plain REFERENCES. Almost every other column is still optional. If you already have schema.sql from part 1, the command below writes the same file again; if you are starting here, it creates it.
cat > schema.sql <<'SQL'
-- Clinic booking database, part 1: tables, keys and relationships.
-- Business rules (NOT NULL, CHECK, UNIQUE email, ON DELETE behaviour,
-- no double-booking) are added in part 2.
CREATE TABLE clinics (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
public_id uuid NOT NULL DEFAULT uuidv7() UNIQUE,
name text,
city text,
country text, -- ISO 3166-1 code, e.g. NG, KE
timezone text, -- IANA name, e.g. Africa/Lagos
currency text, -- ISO 4217 code, e.g. NGN, KES
phone text,
created_at timestamptz DEFAULT now()
);
CREATE TABLE opening_hours (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
clinic_id bigint REFERENCES clinics (id),
weekday smallint, -- ISO weekday: 1 = Monday ... 7 = Sunday
opens time,
closes time
);
CREATE TABLE practitioners (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
public_id uuid NOT NULL DEFAULT uuidv7() UNIQUE,
clinic_id bigint REFERENCES clinics (id),
full_name text,
specialty text,
email text,
created_at timestamptz DEFAULT now()
);
CREATE TABLE patients (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
public_id uuid NOT NULL DEFAULT uuidv7() UNIQUE,
clinic_id bigint REFERENCES clinics (id), -- where they registered
full_name text,
phone text, -- E.164 format, e.g. +2348000000001
email text,
date_of_birth date,
preferred_language text, -- language tag for reminders, e.g. en, yo, sw
created_at timestamptz DEFAULT now()
);
CREATE TABLE services (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
public_id uuid NOT NULL DEFAULT uuidv7() UNIQUE,
clinic_id bigint REFERENCES clinics (id),
name text,
duration_minutes integer,
fee numeric(12, 2) -- current price, in the clinic's currency
);
CREATE TABLE practitioner_services (
practitioner_id bigint REFERENCES practitioners (id),
service_id bigint REFERENCES services (id),
PRIMARY KEY (practitioner_id, service_id)
);
CREATE TABLE appointments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
public_id uuid NOT NULL DEFAULT uuidv7() UNIQUE,
practitioner_id bigint REFERENCES practitioners (id),
patient_id bigint REFERENCES patients (id),
service_id bigint REFERENCES services (id),
starts_at timestamptz,
ends_at timestamptz,
status text DEFAULT 'booked', -- booked, completed, cancelled, no_show
fee numeric(12, 2), -- price agreed when booked
notes text,
created_at timestamptz DEFAULT now()
);
SQLThe examples below refer to rows by their ID (clinic 1, patient 2), so start from an empty clinic database. The next command deletes any existing database called clinic, with everything in it. If yours holds anything you want to keep, back it up first as in /tutorials/back-up-and-restore-postgresql-with-pg-dump.
sudo -u postgres dropdb --if-exists clinic
sudo -u postgres createdb clinic
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic < schema.sqlThe < is read by your own shell, so the postgres user does not need permission to open your home folder. ON_ERROR_STOP=1 makes psql stop at the first error and exit with a non-zero code, which is what you want when loading a schema.
Add two clinics, one in Lagos and one in Nairobi, with a practitioner, a service and a patient or two each, and one appointment:
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
INSERT INTO clinics (name, city, country, timezone, currency) VALUES
('Yaba Family Clinic', 'Lagos', 'NG', 'Africa/Lagos', 'NGN'),
('Kilimani Health Centre', 'Nairobi', 'KE', 'Africa/Nairobi', 'KES');
INSERT INTO practitioners (clinic_id, full_name, email) VALUES
(1, 'Dr Ngozi Eze', 'ngozi.eze@example.com'),
(2, 'Dr Wanjiru Kamau', 'wanjiru.kamau@example.com');
INSERT INTO patients (clinic_id, full_name, email, phone, date_of_birth) VALUES
(1, 'Amara Obi', 'amara@example.com', '+2348031112222', '1990-04-12'),
(1, 'Tunde Bakare', NULL, '+2348124445555', '1984-11-02');
INSERT INTO services (clinic_id, name, duration_minutes, fee) VALUES
(1, 'General consultation', 30, 15000.00),
(2, 'Dental check-up', 45, 3500.00);
INSERT INTO practitioner_services VALUES (1, 1), (2, 2);
INSERT INTO opening_hours (clinic_id, weekday, opens, closes)
SELECT 1, d, '08:00', '17:00' FROM generate_series(1, 5) AS d;
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (1, 1, 1, '2026-12-01 09:00+01', '2026-12-01 09:30+01');
SQLFees are stored in each clinic's own currency, naira in Lagos and shillings in Nairobi. Tunde has no email address, only a phone number, which is common for patients who book by phone or WhatsApp. The schema has to allow that.
Now try four rows that break the clinic's rules:
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
-- Ends an hour before it starts.
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (1, 2, 1, '2026-12-01 10:00+01', '2026-12-01 09:00+01');
-- Dr Eze already sees Amara from 09:00 to 09:30.
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (1, 2, 1, '2026-12-01 09:15+01', '2026-12-01 09:45+01');
-- A negative fee.
INSERT INTO services (clinic_id, name, duration_minutes, fee)
VALUES (1, 'Refund hack', 30, -500);
-- No name, and Amara's email in capitals.
INSERT INTO patients (full_name, email) VALUES (NULL, 'AMARA@example.com');
SQLCheck it worked
psql prints INSERT 0 1 four times. Every bad row went in, even with ON_ERROR_STOP on, because nothing in the schema says they are wrong. That is the gap this part closes.
Step 2 · Remove the bad rows and require the columns that matter
A constraint cannot be added while rows in the table already break it, so delete the four bad rows first. On your own data this is the moment to find and fix rows, not delete them blindly; the last but one step shows a way to add a rule without fixing everything first.
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
DELETE FROM appointments WHERE id > 1;
DELETE FROM services WHERE fee < 0;
DELETE FROM patients WHERE full_name IS NULL;
SQLThen decide, column by column, what the app cannot work without. A clinic needs a name, a city, a country, a time zone and a currency. A practitioner needs a clinic and a name. A service needs everything. An appointment needs a practitioner, a patient, a service, a start, an end and a status. A patient needs a name, but email, phone and date of birth stay optional for now.
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
ALTER TABLE clinics
ALTER COLUMN name SET NOT NULL,
ALTER COLUMN city SET NOT NULL,
ALTER COLUMN country SET NOT NULL,
ALTER COLUMN timezone SET NOT NULL,
ALTER COLUMN currency SET NOT NULL;
ALTER TABLE practitioners
ALTER COLUMN clinic_id SET NOT NULL,
ALTER COLUMN full_name SET NOT NULL;
ALTER TABLE patients
ALTER COLUMN full_name SET NOT NULL;
ALTER TABLE services
ALTER COLUMN clinic_id SET NOT NULL,
ALTER COLUMN name SET NOT NULL,
ALTER COLUMN duration_minutes SET NOT NULL,
ALTER COLUMN fee SET NOT NULL;
ALTER TABLE opening_hours
ALTER COLUMN clinic_id SET NOT NULL,
ALTER COLUMN weekday SET NOT NULL,
ALTER COLUMN opens SET NOT NULL,
ALTER COLUMN closes SET NOT NULL;
ALTER TABLE appointments
ALTER COLUMN practitioner_id SET NOT NULL,
ALTER COLUMN patient_id SET NOT NULL,
ALTER COLUMN service_id SET NOT NULL,
ALTER COLUMN starts_at SET NOT NULL,
ALTER COLUMN ends_at SET NOT NULL,
ALTER COLUMN status SET NOT NULL;
SQLDo the NOT NULL work first, before the CHECK rules in the next step. A CHECK passes when its expression comes out as NULL, so CHECK (ends_at > starts_at) on its own would still let through an appointment with no end time.
Since PostgreSQL 18, each NOT NULL is also stored as a named constraint in pg_constraint, with a generated name something like patients_full_name_not_null. Now try a patient with no name. This script has no ON_ERROR_STOP, so psql reports the error and carries on, which is what you want when the point is to watch statements fail.
sudo -u postgres psql -d clinic <<'SQL'
INSERT INTO patients (email, phone) VALUES ('no.name@example.com', '+254712345678');
SQLCheck it worked
psql prints something like:
ERROR: null value in column "full_name" of relation "patients" violates not-null constraint
DETAIL: Failing row contains (...).The error names the table and column. Running sudo -u postgres psql -d clinic -c '\d patients' shows not null in the Nullable column for full_name.
Step 3 · Write the value rules as named CHECK constraints
A CHECK constraint is a true-or-false expression about one row. Give each one a name that reads as the rule itself. When it fails, the name is in the error message, and appointments_ends_after_starts tells a developer far more at 2 a.m. than the generated appointments_check1.
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
ALTER TABLE appointments
ADD CONSTRAINT appointments_ends_after_starts
CHECK (ends_at > starts_at),
ADD CONSTRAINT appointments_status_known
CHECK (status IN ('booked', 'arrived', 'completed', 'cancelled', 'no_show'));
ALTER TABLE services
ADD CONSTRAINT services_fee_not_negative
CHECK (fee >= 0),
ADD CONSTRAINT services_duration_sensible
CHECK (duration_minutes BETWEEN 5 AND 480);
ALTER TABLE opening_hours
ADD CONSTRAINT opening_hours_weekday_iso
CHECK (weekday BETWEEN 1 AND 7),
ADD CONSTRAINT opening_hours_closes_after_opens
CHECK (closes > opens);
ALTER TABLE patients
ADD CONSTRAINT patients_has_contact
CHECK (email IS NOT NULL OR phone IS NOT NULL);
SQLA few choices to note:
- A fee of zero is allowed, because some clinics run free screening days.
weekdayfollows ISO numbering, 1 for Monday to 7 for Sunday, which is whatextract(isodow FROM ...)returns. Write the convention into the constraint so nobody has to guess.patients_has_contactis a rule across two columns: a patient may have no email or no phone, but not neither. A clinic has to be able to send a reminder somehow.statususes the list from part 1's comment, plusarrived, which this part adds so the front desk can mark a patient as checked in and waiting; that is the status a waiting-room screen needs. A separateappointment_statusestable with a foreign key is the other common choice; it is easier to extend without a schema change, at the cost of a join.
Now try one row against each rule:
sudo -u postgres psql -d clinic <<'SQL'
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (1, 2, 1, '2026-12-01 10:00+01', '2026-12-01 09:00+01');
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at, status)
VALUES (1, 2, 1, '2026-12-01 11:00+01', '2026-12-01 11:30+01', 'Booked');
INSERT INTO services (clinic_id, name, duration_minutes, fee)
VALUES (1, 'Refund hack', 30, -500);
INSERT INTO patients (full_name) VALUES ('Kofi Mensah');
SQLCheck it worked
All four are refused, each with a message naming the rule, something like:
ERROR: new row for relation "appointments" violates check constraint "appointments_ends_after_starts"
ERROR: new row for relation "appointments" violates check constraint "appointments_status_known"
ERROR: new row for relation "services" violates check constraint "services_fee_not_negative"
ERROR: new row for relation "patients" violates check constraint "patients_has_contact"Each error is followed by a DETAIL line showing the failing row. Note that 'Booked' with a capital B fails: string comparison in a CHECK is case-sensitive, so the app has to send exactly booked.
Step 4 · Make email addresses unique whatever their case
Amara@Example.com and amara@example.com reach the same inbox, so the clinic should treat them as one address. A plain UNIQUE (email) constraint compares the text exactly and would let both in. A unique constraint can only list columns, so the case-insensitive rule is a unique index on an expression instead:
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
CREATE UNIQUE INDEX patients_email_lower_key ON patients (lower(email));
CREATE UNIQUE INDEX practitioners_email_lower_key ON practitioners (lower(email));
SQLIf CREATE UNIQUE INDEX fails on your own data with could not create unique index, two rows already share an address. Find them with SELECT lower(email), count(*) FROM patients GROUP BY 1 HAVING count(*) > 1; and merge or correct them first.
The index also makes look-ups by lower(email) fast, so the app's sign-in query should compare lower(email) = lower($1) to use it. Store the address as the patient typed it; the index only decides what counts as the same.
Try a second Amara, then two patients who have no email at all:
sudo -u postgres psql -d clinic <<'SQL'
INSERT INTO patients (full_name, email, phone)
VALUES ('Amara O.', 'Amara@Example.COM', '+2348030000000');
INSERT INTO patients (full_name, phone) VALUES
('Kofi Mensah', '+233201234567'),
('Achieng Otieno', '+254722000111');
SQLCheck it worked
The first insert fails with something like:
ERROR: duplicate key value violates unique constraint "patients_email_lower_key"
DETAIL: Key (lower(email))=(amara@example.com) already exists.The second succeeds with INSERT 0 2. A unique index treats each NULL as different from every other NULL, so any number of phone-only patients can share the empty email column. The error says "unique constraint" even though you created an index; PostgreSQL enforces both the same way.
Step 5 · Choose what happens when a referenced row is deleted
Part 1's REFERENCES clauses already stop an appointment from pointing at a patient who does not exist. What they do not say is what should happen when someone deletes a clinic, a practitioner or a patient that other rows point to. The default, NO ACTION, refuses the delete, but nobody chose it. Make the choice on purpose, table by table:
- Appointments are medical and financial records. Deleting a patient, practitioner or service that has appointments must fail:
ON DELETE RESTRICT. Retiring a practitioner is a status change, not a delete. - Practitioners and services belong to a clinic and have their own history. Deleting a clinic that still has them must fail too:
RESTRICT. - A patient's
clinic_idonly records where they first registered, and part 1 leaves it optional; patients are free to book at any clinic. Losing that clinic should not lose the patient or their appointments, so the column is cleared instead:ON DELETE SET NULL. - Opening hours and the practitioner-to-service links mean nothing without their parent. When the parent goes, they should go with it:
ON DELETE CASCADE.
RESTRICT and NO ACTION both refuse the delete. The difference is timing: RESTRICT checks at once, while NO ACTION can be deferred to the end of the transaction. Pick RESTRICT when the answer is "never".
Part 1's constraints have the names PostgreSQL generated, such as appointments_patient_id_fkey. Replace each with a named one. Each ALTER TABLE drops and adds in one statement, and the whole script runs in one transaction, so there is no moment when a reference goes unchecked.
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
BEGIN;
ALTER TABLE appointments
DROP CONSTRAINT appointments_practitioner_id_fkey,
DROP CONSTRAINT appointments_patient_id_fkey,
DROP CONSTRAINT appointments_service_id_fkey,
ADD CONSTRAINT appointments_practitioner_fk FOREIGN KEY (practitioner_id)
REFERENCES practitioners (id) ON DELETE RESTRICT,
ADD CONSTRAINT appointments_patient_fk FOREIGN KEY (patient_id)
REFERENCES patients (id) ON DELETE RESTRICT,
ADD CONSTRAINT appointments_service_fk FOREIGN KEY (service_id)
REFERENCES services (id) ON DELETE RESTRICT;
ALTER TABLE practitioners
DROP CONSTRAINT practitioners_clinic_id_fkey,
ADD CONSTRAINT practitioners_clinic_fk FOREIGN KEY (clinic_id)
REFERENCES clinics (id) ON DELETE RESTRICT;
ALTER TABLE patients
DROP CONSTRAINT patients_clinic_id_fkey,
ADD CONSTRAINT patients_clinic_fk FOREIGN KEY (clinic_id)
REFERENCES clinics (id) ON DELETE SET NULL;
ALTER TABLE services
DROP CONSTRAINT services_clinic_id_fkey,
ADD CONSTRAINT services_clinic_fk FOREIGN KEY (clinic_id)
REFERENCES clinics (id) ON DELETE RESTRICT;
ALTER TABLE opening_hours
DROP CONSTRAINT opening_hours_clinic_id_fkey,
ADD CONSTRAINT opening_hours_clinic_fk FOREIGN KEY (clinic_id)
REFERENCES clinics (id) ON DELETE CASCADE;
ALTER TABLE practitioner_services
DROP CONSTRAINT practitioner_services_practitioner_id_fkey,
DROP CONSTRAINT practitioner_services_service_id_fkey,
ADD CONSTRAINT practitioner_services_practitioner_fk FOREIGN KEY (practitioner_id)
REFERENCES practitioners (id) ON DELETE CASCADE,
ADD CONSTRAINT practitioner_services_service_fk FOREIGN KEY (service_id)
REFERENCES services (id) ON DELETE CASCADE;
COMMIT;
SQLIf psql reports that a constraint such as appointments_patient_id_fkey does not exist, your part 1 schema named it differently. List the real names with sudo -u postgres psql -d clinic -c '\d appointments' and use those in the DROP CONSTRAINT lines.
PostgreSQL does not index the referencing columns (appointments.patient_id and the rest) for you. Part 4 adds the indexes these look-ups need.
Now try both behaviours. Open a short-lived pop-up clinic with Saturday hours, then close it:
sudo -u postgres psql -d clinic <<'SQL'
-- Amara has an appointment, so she cannot be deleted.
DELETE FROM patients WHERE full_name = 'Amara Obi';
-- There is no patient 999.
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (1, 999, 1, '2026-12-01 11:00+01', '2026-12-01 11:30+01');
-- Yaba has practitioners and services, so it cannot be deleted.
DELETE FROM clinics WHERE name = 'Yaba Family Clinic';
-- A pop-up clinic with opening hours and nothing else.
INSERT INTO clinics (name, city, country, timezone, currency)
VALUES ('Ikeja Pop-up Clinic', 'Lagos', 'NG', 'Africa/Lagos', 'NGN');
INSERT INTO opening_hours (clinic_id, weekday, opens, closes)
SELECT id, 6, '09:00', '13:00' FROM clinics WHERE name = 'Ikeja Pop-up Clinic';
SELECT count(*) AS hours_before FROM opening_hours;
DELETE FROM clinics WHERE name = 'Ikeja Pop-up Clinic';
SELECT count(*) AS hours_after FROM opening_hours;
SQLCheck it worked
The first three statements fail, with errors something like:
ERROR: update or delete on table "patients" violates RESTRICT setting of foreign key constraint "appointments_patient_fk" on table "appointments"
ERROR: insert or update on table "appointments" violates foreign key constraint "appointments_patient_fk"
ERROR: update or delete on table "clinics" violates RESTRICT setting of foreign key constraint "practitioners_clinic_fk" on table "practitioners"The third may name services_clinic_fk instead; both rules block the delete, and PostgreSQL reports whichever it checks first. patients_clinic_fk never blocks it: on its own it would only clear Amara's and Tunde's clinic_id, and because the delete fails, even that is rolled back. The pop-up clinic goes cleanly: hours_before is 6 and hours_after is 5, because its Saturday row was deleted with it.
Step 6 · Stop double-booking with an exclusion constraint
The most important rule in a booking system is that a practitioner cannot be in two appointments at once. No CHECK can say that, because it is a rule about pairs of rows, and a UNIQUE constraint only catches equal values, not overlapping times. Checking in the app is not enough either: two receptionists clicking "book" in the same second can both read the slot as free and both insert.
An exclusion constraint states the rule directly: no two rows where practitioner_id is equal and the time ranges overlap. PostgreSQL enforces it with a GiST index. The btree_gist extension, which ships with PostgreSQL, lets that index handle the plain = on a bigint column alongside the range overlap.
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
CREATE EXTENSION IF NOT EXISTS btree_gist;
ALTER TABLE appointments
ADD CONSTRAINT appointments_no_double_booking
EXCLUDE USING gist (
practitioner_id WITH =,
tstzrange(starts_at, ends_at) WITH &&
)
WHERE (status <> 'cancelled');
SQLReading it piece by piece:
tstzrange(starts_at, ends_at)builds a time range from the two columns. By default the range includes its start and excludes its end, written[). An appointment from 09:00 to 09:30 and one from 09:30 to 10:00 therefore do not overlap, which is how a diary works.&&is the overlap operator for ranges.WHERE (status <> 'cancelled')makes it a partial constraint. A cancelled appointment keeps its row for the history, but stops holding the slot.
Because the times are timestamptz, the rule holds across time zones. The Lagos and Nairobi clinics store their times as absolute moments, so 10:00 in Nairobi and 08:00 in Lagos are the same instant. PostgreSQL 18 also accepts WITHOUT OVERLAPS in a primary key or unique constraint, which does the same job when you store a range column; it cannot take a WHERE, so the exclusion constraint fits the cancelled-appointment rule better.
Now try four bookings and a cancellation:
sudo -u postgres psql -d clinic <<'SQL'
-- Overlaps Amara's 09:00 to 09:30 with Dr Eze: refused.
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (1, 2, 1, '2026-12-01 09:15+01', '2026-12-01 09:45+01');
-- Starts the moment Amara's ends: accepted.
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (1, 2, 1, '2026-12-01 09:30+01', '2026-12-01 10:00+01');
-- Same moment, different practitioner: accepted.
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
SELECT 2, id, 2, '2026-12-01 09:15+01', '2026-12-01 10:00+01'
FROM patients WHERE full_name = 'Kofi Mensah';
-- Amara cancels, and Tunde takes her slot: accepted.
UPDATE appointments SET status = 'cancelled' WHERE id = 1;
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (1, 2, 1, '2026-12-01 09:00+01', '2026-12-01 09:30+01');
SELECT practitioner_id, patient_id, status,
to_char(starts_at AT TIME ZONE 'Africa/Lagos', 'HH24:MI') AS starts,
to_char(ends_at AT TIME ZONE 'Africa/Lagos', 'HH24:MI') AS ends
FROM appointments ORDER BY practitioner_id, starts_at, status;
SQLCheck it worked
Only the first insert fails, with something like:
ERROR: conflicting key value violates exclusion constraint "appointments_no_double_booking"
DETAIL: Key (practitioner_id, tstzrange(starts_at, ends_at))=(1, ["2026-12-01 08:15:00+00","2026-12-01 08:45:00+00")) conflicts with existing key (1, ["2026-12-01 08:00:00+00","2026-12-01 08:30:00+00")).The DETAIL shows times in the server's time zone, so yours may differ. The final listing has four rows: Dr Eze (practitioner 1) with a booked 09:00 to 09:30, a cancelled 09:00 to 09:30 and a booked 09:30 to 10:00, and Dr Kamau (practitioner 2) with a booked 09:15 to 10:00, all in Lagos time.
The constraint does not stop one patient from being in two places at once. If your clinics need that rule too, add a second exclusion constraint with patient_id WITH = in place of practitioner_id.
Step 7 · Add a rule to a full table with NOT VALID and VALIDATE
So far every table has had a handful of rows, and each ADD CONSTRAINT checked them in an instant. On a live table with millions of appointments, which you build in part 3, adding a CHECK the plain way scans the whole table while holding a lock that blocks every read and write. And if one old row breaks the rule, the whole command fails after all that waiting.
NOT VALID splits the job in two. The constraint is added at once, without scanning, and applies to every new or changed row from that moment. VALIDATE CONSTRAINT checks the existing rows later, under a lighter lock that lets reads and writes carry on. This works for CHECK and foreign key constraints, and since PostgreSQL 18 for NOT NULL too. It does not work for unique or exclusion constraints.
Here is the scenario. An old import from a paper diary left a nine-hour "all day" block in Dr Kamau's diary. The clinic now wants a rule that no appointment is longer than four hours.
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
-- The legacy row, from before the rule existed.
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (2, 2, 2, '2026-11-20 08:00+03', '2026-11-20 17:00+03');
ALTER TABLE appointments
ADD CONSTRAINT appointments_at_most_four_hours
CHECK (ends_at - starts_at <= interval '4 hours') NOT VALID;
SQLThe rule is now live for new rows, but the old one has not been checked. Try a new long booking, then try to validate:
sudo -u postgres psql -d clinic <<'SQL'
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (1, 1, 1, '2026-12-02 08:00+01', '2026-12-02 14:00+01');
ALTER TABLE appointments VALIDATE CONSTRAINT appointments_at_most_four_hours;
SELECT id, practitioner_id, ends_at - starts_at AS length
FROM appointments
WHERE NOT (ends_at - starts_at <= interval '4 hours');
SQLBoth statements fail, something like:
ERROR: new row for relation "appointments" violates check constraint "appointments_at_most_four_hours"
ERROR: check constraint "appointments_at_most_four_hours" of relation "appointments" is violated by some rowThe SELECT finds the culprit: one row for practitioner 2, with a length of 09:00:00. Fix it (here the block was really a 45-minute dental check-up), then validate again:
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
UPDATE appointments
SET ends_at = starts_at + interval '45 minutes'
WHERE ends_at - starts_at > interval '4 hours';
ALTER TABLE appointments VALIDATE CONSTRAINT appointments_at_most_four_hours;
SELECT conname, convalidated
FROM pg_constraint
WHERE conname = 'appointments_at_most_four_hours';
SQLCheck it worked
psql prints UPDATE 1, then ALTER TABLE, then one row with convalidated set to t. Before the VALIDATE it was f. A constraint that is still NOT VALID shows that way in \d appointments too, which is worth checking for after any migration.
Step 8 · List the rules, save the schema and hand over to part 3
The database now holds the clinic's rules. List them in one place, from the system catalogue:
sudo -u postgres psql -d clinic <<'SQL'
SELECT conrelid::regclass AS table_name,
conname,
CASE contype
WHEN 'c' THEN 'check'
WHEN 'f' THEN 'foreign key'
WHEN 'u' THEN 'unique'
WHEN 'x' THEN 'exclusion'
END AS kind
FROM pg_constraint
WHERE connamespace = 'public'::regnamespace
AND contype IN ('c', 'f', 'u', 'x')
ORDER BY 1, 3, 2;
SELECT indexname FROM pg_indexes
WHERE schemaname = 'public' AND indexname LIKE '%email_lower_key';
SQLThe first query lists 23 rows: 8 checks, 9 foreign keys, 5 unique constraints on the public_id columns and the one exclusion constraint. The two email indexes appear only in the second query, because a unique index is not a row in pg_constraint. Primary keys (p) and not-null constraints (n) are left out to keep the list short.
The constraint names are what the app should use to turn errors into messages a receptionist understands. Every error also carries a five-character SQLSTATE code. Turn on verbose errors and try the double booking once more:
sudo -u postgres psql -d clinic <<'SQL'
\set VERBOSITY verbose
INSERT INTO appointments (practitioner_id, patient_id, service_id, starts_at, ends_at)
VALUES (2, 1, 2, '2026-12-01 09:30+01', '2026-12-01 10:15+01');
SQLThe error now starts with something like ERROR: 23P01: conflicting key value violates exclusion constraint "appointments_no_double_booking". The codes you will meet from this part are 23502 (not null), 23514 (check), 23505 (unique), 23503 (foreign key) and 23P01 (exclusion). Database drivers expose the code and the constraint name as separate fields, so the app can check for 23P01 with appointments_no_double_booking and show "That time has just been taken, please pick another" instead of a stack trace.
Save the schema as it now stands, so you have it in a file:
cd ~/clinic-demo
sudo -u postgres pg_dump --schema-only clinic > schema-after-part-2.sql
grep -E 'appointments_no_double_booking|appointments_at_most_four_hours' schema-after-part-2.sqlPart 3 fills the tables with millions of generated rows and needs them empty, with the IDs starting from 1. The next command deletes every row you added in this part. It keeps the tables and every constraint.
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
TRUNCATE appointments, practitioner_services, opening_hours, services,
practitioners, patients, clinics
RESTART IDENTITY;
SELECT (SELECT count(*) FROM appointments) AS appointments,
(SELECT count(*) FROM clinics) AS clinics,
(SELECT count(*) FROM pg_constraint
WHERE connamespace = 'public'::regnamespace
AND contype IN ('c', 'f', 'u', 'x')) AS rules;
SQLCheck it worked
grep prints a few lines from schema-after-part-2.sql, including the CONSTRAINT appointments_at_most_four_hours CHECK line inside the CREATE TABLE appointments statement, and the ADD CONSTRAINT appointments_no_double_booking EXCLUDE USING gist line. The final query shows 0 appointments, 0 clinics and 23 rules. Leave the clinic database and ~/clinic-demo in place for part 3.
Next steps
- Fill the tables with two years of realistic bookings that still pass every rule from this part: /tutorials/fill-the-clinic-database-with-realistic-test-data.
- Go back over the tables and keys these rules sit on: /tutorials/design-the-clinic-booking-schema-tables-and-relationships.
- See why the app alone cannot stop two bookings arriving in the same second: /tutorials/understand-postgresql-transactions-and-isolation-levels.
- Add the indexes the foreign keys and the diary queries need: /tutorials/index-the-clinic-database-for-the-queries-it-really-runs.
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