skip to content

the schema design interview

a booking system from requirements to constraints, thought out loud.

address
everything.deep_dives.schema_interview
part
part 18, deep dives and interviews
chapter
chapter 7 of 10
reading time
9 min

the schema round isn't about drawing boxes. it's about turning each requirement into something the database enforces: keys for identity, foreign keys for references, an exclusion constraint so two bookings can't overlap, a temporal key so a room can't have two prices for one night, indexes chosen for the queries you'll actually run, and row-level security so one hotel never sees another's guests.

here's a booking system, thought out loud, and every constraint run for real.

the picture

you know how a schema question starts with "design a booking system" and an empty whiteboard, and it's tempting to start drawing tables? the interviewer wants to hear the questions first. which rules must never be broken, even by a buggy app? those go in the schema. everything else can live in code.

think of the schema as the house rules written on the wall, not in the staff handbook. a new employee (a new service, a script someone runs at 2 am) will skip the handbook. they can't skip the wall.

the requirements, as an interviewer would give them, and what each one becomes:

  • hotel_id on every tenant row + row-level security
  • ├── a hotel has rooms, numbered per hotelrooms: surrogate key, UNIQUE (hotel_id, room_no)
  • └── guests are people, found by emailguests: UNIQUE index on lower(email)
  • EXCLUDE USING gist (room_id WITH =, stay WITH &&)
  • ├── cancelled bookings free the room... WHERE (status = 'confirmed')
  • └── check-out day = next check-in day is finedaterange, [) bounds
  • a room has one price per nightPRIMARY KEY (room_id, valid WITHOUT OVERLAPS)
  • "show my upcoming stays" must be fastindex on bookings (guest_id, lower(stay))
from the brief to the schema. each requirement turns into one thing postgres enforces; the rest of the chapter builds them.

entities and keys

four tables do it: hotels, rooms, guests, bookings, plus room_rates for prices (from requirements to tables). every table gets a surrogate int identity key, because natural keys here change (a guest's email, a room renumbered in a refit), and the natural keys get UNIQUE constraints anyway, so they can't be duplicated (primary keys, natural and surrogate). room numbers are unique per hotel, so that's a composite UNIQUE. emails are unique regardless of case, so the unique index is on lower(email).

sqlempty db · ext=btree_gist · session hotel
CREATE TABLE hotels (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL UNIQUE);
CREATE TABLE rooms (
  id       int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  hotel_id int NOT NULL REFERENCES hotels,
  room_no  text NOT NULL,
  beds     int NOT NULL CHECK (beds BETWEEN 1 AND 6),
  UNIQUE (hotel_id, room_no)
);
CREATE TABLE guests (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL, name text NOT NULL);
CREATE UNIQUE INDEX guests_email ON guests (lower(email));
INSERT INTO hotels (name) VALUES ('harbour view'), ('the old mill');
INSERT INTO rooms (hotel_id, room_no, beds) VALUES (1, '101', 2), (1, '102', 2), (2, '1', 4);
INSERT INTO guests (email, name) VALUES ('ada@example.com', 'Ada Lovelace'), ('grace@example.com', 'Grace Hopper');
INSERT INTO guests (email, name) VALUES ('Ada@Example.com', 'Ada again');
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE TABLE
#3 · CREATE TABLE
#4 · CREATE INDEX
#5 · INSERT 0 2
#6 · INSERT 0 3
#7 · INSERT 0 2
#8 · ERROR 23505
ERROR 23505: duplicate key value violates unique constraint "guests_email"
DETAIL: Key (lower(email))=(ada@example.com) already exists.

the last insert is the point: the same email in different case is refused (NOT NULL, CHECK and UNIQUE, partial and expression indexes).

no double bookings

the requirement every interviewer is waiting for: two confirmed bookings of one room can't overlap. a UNIQUE constraint can't say "overlap", and a check in the application has a race: two requests both look, both see the room free, both insert (write skew). you could fix the race with SERIALIZABLE and retries (postgres vs InnoDB watches exactly that race), or with a lock on the room row. the schema answer is better: an exclusion constraint, which the database checks against every other row, under concurrency, through an index (time ranges and temporal keys, range types).

sqlempty db · ext=btree_gist · session hotel
continues session hotel (1 earlier block run first)
CREATE TABLE bookings (
  id       int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  hotel_id int NOT NULL REFERENCES hotels,
  room_id  int NOT NULL REFERENCES rooms,
  guest_id int NOT NULL REFERENCES guests,
  stay     daterange NOT NULL CHECK (NOT isempty(stay)),
  status   text NOT NULL DEFAULT 'confirmed' CHECK (status IN ('confirmed', 'cancelled')),
  EXCLUDE USING gist (room_id WITH =, stay WITH &&) WHERE (status = 'confirmed')
);
INSERT INTO bookings (hotel_id, room_id, guest_id, stay) VALUES (1, 1, 1, '[2026-12-20,2026-12-27)');
INSERT INTO bookings (hotel_id, room_id, guest_id, stay) VALUES (1, 1, 2, '[2026-12-24,2026-12-29)');
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 1
#3 · ERROR 23P01
ERROR 23P01: conflicting key value violates exclusion constraint "bookings_room_id_stay_excl"
DETAIL: Key (room_id, stay)=(1, [2026-12-24,2026-12-29)) conflicts with existing key (room_id, stay)=(1, [2026-12-20,2026-12-27)).

read the constraint out loud: "no two rows where room_id is = and stay is && (overlaps), counting only confirmed rows". room_id WITH = inside a GiST index is why btree_gist is needed. the half-open [) range means a guest checking out on the 27th doesn't block one checking in on the 27th. and the WHERE makes it a partial constraint, so cancelling a booking frees the room without deleting history (history, audit and soft delete).

try =
bookings.sql
  1. 1INSERT INTO bookings (hotel_id, room_id, guest_id, stay) VALUES (1, 1, 2, '[2026-12-24,2026-12-29)');
ERROR: conflicting key value violates exclusion constraint "bookings_room_id_stay_excl"SQLSTATE 23P01

room 101 is already booked from the 20th to the 27th. an overlapping stay is refused by the exclusion constraint, with the conflicting row in the message.

real output, postgres 18.6 (PGlite 0.5.12) · booking
five writes against the schema above, captured. pick one: the refusals name the constraint and, for an overlap, the row it collides with.
predict the output
room 101: confirmed '[2026-12-20,2026-12-27)'. insert '[2026-12-27,2026-12-30)' for the same room?
sql
INSERT INTO bookings (hotel_id, room_id, guest_id, stay)
VALUES (1, 1, 2, '[2026-12-27,2026-12-30)');

a temporal key for prices

prices change over time, and a room must have exactly one price for any night. that's a key that's unique per moment: postgres 18's WITHOUT OVERLAPS pg 18+.

sqlempty db · ext=btree_gist · session hotel
continues session hotel (2 earlier blocks run first)
CREATE TABLE room_rates (
  room_id int NOT NULL REFERENCES rooms,
  valid   daterange NOT NULL,
  price   numeric(8,2) NOT NULL CHECK (price > 0),
  PRIMARY KEY (room_id, valid WITHOUT OVERLAPS)
);
INSERT INTO room_rates VALUES (1, '[2026-01-01,2026-12-01)', 120.00), (1, '[2026-12-01,2027-01-01)', 180.00);
SELECT price FROM room_rates WHERE room_id = 1 AND valid @> date '2026-12-24';
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 2
#3 · SELECT 1
pricenumeric
180.00
(1 row)

why a temporal primary key here, but an EXCLUDE for bookings? WITHOUT OVERLAPS is a real primary key (it can be referenced, and it refuses empty ranges), but it can't have a WHERE. bookings needed "only confirmed ones count", so they got the more general tool. both are a GiST index underneath.

indexes for the queries

don't index by guessing. list the queries the product will run, and check each has an index that answers it:

sqlempty db · ext=btree_gist · session hotel
continues session hotel (3 earlier blocks run first)
CREATE INDEX bookings_guest ON bookings (guest_id, lower(stay));
SELECT tablename, indexname, indexdef
FROM pg_indexes
WHERE tablename IN ('bookings', 'room_rates', 'rooms', 'guests')
ORDER BY tablename, indexname;
output, from postgres 18.6
#1 · CREATE INDEX
#2 · SELECT 8
tablenamenameindexnamenameindexdeftext
bookingsbookings_guest
bookingsbookings_pkey
bookingsbookings_room_id_stay_excl
guestsguests_email
guestsguests_pkey
room_ratesroom_rates_pkey
roomsrooms_hotel_id_room_no_key
roomsrooms_pkeyCREATE UNIQUE INDEX rooms_pkey ON public.rooms USING btree (id)
(8 rows)

"is room 101 free on these dates?" is the exclusion constraint's own GiST index on (room_id, stay), as long as the query says status = 'confirmed' too, because that index is partial. "rooms of a hotel" is the UNIQUE (hotel_id, room_no) index, hotel_id first. "a guest's upcoming stays, soonest first" is bookings_guest: equality on guest_id, then ordered by check-in date, which also makes it the index the guest_id foreign key needs, so deleting a guest doesn't scan bookings (a query tuning casebook, case 9). bookings.room_id is the leading column of the GiST index, but that index skips cancelled rows, so it can't serve the room foreign key's check; rooms are almost never deleted, so that's a choice you can say out loud and skip. (multicolumn indexes, what indexes cost.)

tenants: row-level security

several hotels in one database means every query must filter by hotel, and one forgotten WHERE leaks another hotel's guests. row-level security puts the filter in the table (schemas, roles and row-level security):

sqlempty db · ext=btree_gist · session hotel
continues session hotel (4 earlier blocks run first)
ALTER TABLE bookings ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant ON bookings
  USING (hotel_id = nullif(current_setting('app.hotel_id', true), '')::int);
CREATE ROLE booking_app_demo;
GRANT SELECT, INSERT ON bookings TO booking_app_demo;
SET ROLE booking_app_demo;
SELECT set_config('app.hotel_id', '2', false) IS NOT NULL AS hotel_set;
SELECT id, hotel_id, room_id, stay FROM bookings ORDER BY id;
RESET ROLE;
DROP OWNED BY booking_app_demo;
DROP ROLE booking_app_demo;
output, from postgres 18.6
#1 · ALTER TABLE
#2 · CREATE POLICY
#3 · CREATE ROLE
#4 · GRANT
#5 · SET
#6 · SELECT 1
hotel_setbool
t
(1 row)
#7 · SELECT 0
idint4hotel_idint4room_idint4staydaterange
(0 rows)
#8 · RESET
#9 · DROP OWNED
#10 · DROP ROLE

hotel 2 sees nothing: its one booking isn't in this session's data, and hotel 1's rows are filtered out. the app connects as a role that doesn't own the table (owners bypass RLS unless you FORCE it), and sets app.hotel_id per request, inside the transaction in a pooled setup (set_config(…, true), see connections and pooling). the captured version, with a booking for each hotel:

as =
tenant.sql
  1. 1SET ROLE booking_app;
  2. 2SELECT set_config('app.hotel_id', '1', false) IS NOT NULL AS set;
  3. 3SELECT id, hotel_id, room_id, stay, status FROM bookings ORDER BY id;
the result for hotel 1
idint4hotel_idint4room_idint4staydaterangestatustext
111[2026-12-20,2026-12-27)confirmed
212[2026-12-20,2026-12-27)cancelled
511[2026-12-27,2026-12-30)confirmed
612[2026-12-22,2026-12-25)confirmed
(4 rows)

the app connects as booking_app with hotel 1 in a setting. row-level security shows it hotel 1's bookings only.

real output, postgres 18.6 (PGlite 0.5.12) · booking
the same query as four different callers, captured. with no hotel set, the policy compares against NULL and returns no rows, not all of them. a write for another hotel is refused: a USING policy also checks new rows.

the nullif(…, '') isn't decoration. once a custom setting has been set in a session, "unset" reads back as an empty string, and ''::int is an error, so the policy would fail every query instead of returning nothing.

keylines

  • turn each must-never-break rule into a constraint: keys, foreign keys, CHECK, UNIQUE, EXCLUDE.
  • no overlaps: EXCLUDE USING gist (room_id WITH =, stay WITH &&), partial with WHERE.
  • one value per moment: PRIMARY KEY (…, valid WITHOUT OVERLAPS), postgres 18.
  • [) ranges make back-to-back stays legal.
  • pick indexes from the query list, and cover foreign keys.
  • tenants: hotel_id everywhere plus an RLS policy, and an app role that doesn't own the tables.