AI Hints
Home›PostgreSQL Tutorial›Project: Harbor Events, Part 3
PostgreSQL · Lesson 112 of 120

Project: Safe Bookings

Never oversell.

⏱ 2 min read▶ Video at 1:41:24🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Two guests try to buy the last seats at the same moment. Without care, both succeed, and the show is oversold. A booking function with a row lock makes bookings take turns.

  • Last seats
  • Two buyers
  • Take turns

A booking function

For update locks the event row, so a second booking waits. Then we count seats sold. If there aren't enough, raise exception refuses. Otherwise, insert and return the new ID. We book ten seats at the small loft, three times. Run it. The third booking is refused.

query.sqlsql
CREATE FUNCTION book(p_event int, p_email text, p_seats int) RETURNS int
LANGUAGE plpgsql AS $$
DECLARE cap int; sold int; new_id int;
BEGIN
  SELECT v.capacity INTO cap FROM events e JOIN venues v USING (venue_id)
  WHERE e.event_id = p_event FOR UPDATE OF e;           -- one booking at a time
  SELECT coalesce(sum(seats), 0) INTO sold FROM bookings WHERE event_id = p_event;
  IF sold + p_seats > cap THEN
    RAISE EXCEPTION 'Only % seats left', cap - sold;
  END IF;
  INSERT INTO bookings (event_id, email, seats) VALUES (p_event, p_email, p_seats)
  RETURNING booking_id INTO new_id;
  RETURN new_id;
END $$;

SELECT book(2, 'ana@mail.com', 10), book(2, 'ben@mail.com', 10);
SELECT book(2, 'cy@mail.com', 10);
Output
CREATE FUNCTION
 book | book
------+------
 1193 | 1194
(1 row)

ERROR:  Only 2 seats left
CONTEXT:  PL/pgSQL function book(integer,text,integer) line 8 at RAISE
Also uses _setup.sql
CREATE TABLE venues (
  venue_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name     text NOT NULL UNIQUE,
  city     text NOT NULL,
  capacity integer NOT NULL CHECK (capacity > 0));
CREATE TABLE events (
  event_id  integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  venue_id  integer NOT NULL REFERENCES venues,
  title     text NOT NULL,
  starts_at timestamptz NOT NULL,
  price     numeric(6,2) NOT NULL CHECK (price >= 0));
CREATE TABLE bookings (
  booking_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  event_id   integer NOT NULL REFERENCES events,
  email      text NOT NULL,
  seats      integer NOT NULL CHECK (seats BETWEEN 1 AND 10),
  booked_at  timestamptz NOT NULL DEFAULT now(),
  UNIQUE (event_id, email));
INSERT INTO venues (name, city, capacity) VALUES
  ('Harbor Hall', 'Halifax', 300), ('Pier Theatre', 'Halifax', 120),
  ('Lighthouse Loft', 'Lunenburg', 60);

INSERT INTO events (venue_id, title, starts_at, price)
SELECT 1 + g % 3,
       (ARRAY['Jazz Night', 'Comedy Hour', 'Folk Session', 'Poetry Slam',
              'Sea Shanty Evening', 'Indie Film Night'])[1 + g % 6],
       timestamptz '2026-01-02 19:30' + g * interval '2 days',
       (ARRAY[15, 20, 25, 30])[1 + g % 4]
FROM generate_series(1, 60) g;

SELECT setseed(0.7);
INSERT INTO bookings (event_id, email, seats, booked_at)
SELECT e, 'guest' || c || '@mail.com', 1 + (random() * 2)::int,
       timestamptz '2026-01-01' + random() * interval '100 days'
FROM generate_series(1, 60) e, generate_series(1, 40) c
WHERE random() < 0.5;
Also uses _empty
1

Why it works

The row lock serialises bookings for the same event, while other events stay independent. The check and the insert happen in one transaction. And the error message tells the app exactly what went wrong.

keyvalue
FOR UPDATEone at a time, per event
Same transactioncheck + insert
Other eventsnot blocked
Messageseats left

Summary

A function with a row lock makes overselling impossible. Next, access rules.

Key takeaways
  • FOR UPDATE
  • RAISE
  • No overselling
Next up: Project: Access Rules — who can do what