Final project: an event ticketing database

Topic 2 of 2 in Projects15 min readBeginnerFree course

The brief

Bean & Leaf runs tasting events and workshops — latte art, tea ceremonies, home roasting — at venues in several cities, and has been taking bookings in a spreadsheet. Last month an event was oversold by six seats. You’ve been asked to build a proper database for it.

The shop needs to:

  • record venues, each with a fixed capacity;
  • schedule events at venues, with a start time and a ticket price;
  • keep a list of attendees, identified by email;
  • take bookings — an attendee books one or more seats for an event — and never sell more seats than the venue holds;
  • report on sales: seats sold and revenue per event, the busiest venues, the best customers;
  • give the marketing team a simple, safe way to read the sales figures.

You’ll do it in six steps, using something from every chapter of the course. Try each step yourself before reading the solution.

Final project: an event ticketing database. Four tables: venues (id PK, name, city, capacity CHECK > 0); events (id PK, venue_id FK, title, starts_at timestamptz, price numeric); attendees (id PK, name, email UNIQUE); and bookings (id PK, event_id FK, attendee_id FK, seats CHECK > 0, booked_at). venues to events is one-to-many, events to bookings is one-to-many, and attendees to bookings is one-to-many. The tasks: 1 create the tables with constraints; 2 load sample data; 3 reports — sales per event, busiest venue, top attendees; 4 book seats in a transaction that cannot overbook; 5 add indexes and check plans with EXPLAIN; 6 publish an event_sales view. Everything in the course comes together: design, constraints, joins, aggregates, transactions, indexes and views.

Step 1: design and create the tables

Four kinds of thing, four tables. A booking links an attendee to an event — a many-to-many relationship resolved by a linking table, just like order_items in the shop. Every rule from the brief that can be a constraint, is one:

SQL
CREATE TABLE venues (
    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 (
    id        integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    venue_id  integer NOT NULL REFERENCES venues (id),
    title     text NOT NULL,
    starts_at timestamptz NOT NULL,
    price     numeric(8,2) NOT NULL CHECK (price >= 0)
);

CREATE TABLE attendees (
    id    integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name  text NOT NULL,
    email text NOT NULL UNIQUE CHECK (email LIKE '%_@_%')
);

CREATE TABLE bookings (
    id          integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    event_id    integer NOT NULL REFERENCES events (id),
    attendee_id integer NOT NULL REFERENCES attendees (id),
    seats       integer NOT NULL CHECK (seats BETWEEN 1 AND 10),
    booked_at   timestamptz NOT NULL DEFAULT now(),
    UNIQUE (event_id, attendee_id)
);
Text
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE

Design decisions worth noticing:

  • starts_at is a timestamptz, because the venues are in different time zones and an event happens at one exact moment.
  • price is numeric — money is never floating point.
  • UNIQUE (event_id, attendee_id): one booking per attendee per event (they change the number of seats rather than booking twice), and a maximum of 10 seats per booking.
  • The capacity rule — total seats for an event can’t exceed its venue’s capacity — involves many rows, so a CHECK can’t express it. Step 4 handles it with a transaction.

Step 2: load sample data

SQL
INSERT INTO venues (name, city, capacity) VALUES
  ('The Roastery', 'London',    40),
  ('Leaf Hall',    'Pune',      120),
  ('Harbour Loft', 'Singapore', 60);

INSERT INTO events (venue_id, title, starts_at, price) VALUES
  (1, 'Cupping Masterclass',   '2026-11-10 18:00+00',    45.00),
  (1, 'Latte Art Basics',      '2027-01-15 18:00+00',    25.00),
  (2, 'Tea & Mindfulness',     '2027-01-22 10:00+05:30', 15.00),
  (1, 'Home Roasting 101',     '2027-02-05 18:00+00',    35.00),
  (3, 'Singapore Coffee Fest', '2027-02-20 11:00+08',    40.00);

INSERT INTO attendees (name, email) VALUES
  ('Asha Rao',    'asha.rao@example.com'),
  ('Ben Carter',  'ben.carter@example.com'),
  ('Chen Wei',    'chen.wei@example.com'),
  ('Elena García','elena.garcia@example.com'),
  ('Grace Kim',   'grace.kim@example.com'),
  ('Hugo Martin', 'hugo.martin@example.com'),
  ('Isha Patel',  'isha.patel@example.com'),
  ('Kofi Mensah', 'kofi.mensah@example.com');

INSERT INTO bookings (event_id, attendee_id, seats) VALUES
  (1, 2, 4), (1, 6, 2), (1, 4, 3),
  (2, 1, 10), (2, 2, 8), (2, 3, 6), (2, 4, 10), (2, 5, 4),
  (3, 1, 2), (3, 7, 6), (3, 8, 3),
  (4, 2, 6), (4, 6, 4),
  (5, 3, 2), (5, 5, 5);
Text
INSERT 0 3
INSERT 0 5
INSERT 0 8
INSERT 0 15

The constraints are already earning their keep. Try a few bad rows:

SQL
INSERT INTO venues (name, city, capacity) VALUES ('Pop-up', 'Leeds', 0);
INSERT INTO attendees (name, email) VALUES ('No Email', 'not-an-email');
INSERT INTO bookings (event_id, attendee_id, seats) VALUES (2, 1, 1);
INSERT INTO bookings (event_id, attendee_id, seats) VALUES (99, 1, 1);
Text
ERROR:  new row for relation "venues" violates check constraint "venues_capacity_check"
DETAIL:  Failing row contains (4, Pop-up, Leeds, 0).
ERROR:  new row for relation "attendees" violates check constraint "attendees_email_check"
DETAIL:  Failing row contains (9, No Email, not-an-email).
ERROR:  duplicate key value violates unique constraint "bookings_event_id_attendee_id_key"
DETAIL:  Key (event_id, attendee_id)=(2, 1) already exists.
ERROR:  insert or update on table "bookings" violates foreign key constraint "bookings_event_id_fkey"
DETAIL:  Key (event_id)=(99) is not present in table "events".

Zero capacity, an invalid email, a second booking by the same attendee, and a booking for a non-existent event — all refused by the database itself.

Step 3: business reports

Sales per event, including events with no bookings, with seats left and revenue. Event times are shown in the venue’s local time zone:

SQL
SELECT e.title,
       v.city,
       to_char(e.starts_at AT TIME ZONE
               CASE v.city WHEN 'London' THEN 'Europe/London'
                           WHEN 'Pune' THEN 'Asia/Kolkata'
                           ELSE 'Asia/Singapore' END,
               'DD Mon YYYY HH24:MI') AS local_start,
       COALESCE(sum(b.seats), 0)                AS seats_sold,
       v.capacity - COALESCE(sum(b.seats), 0)   AS seats_left,
       COALESCE(sum(b.seats), 0) * e.price      AS revenue
FROM events AS e
JOIN venues AS v ON v.id = e.venue_id
LEFT JOIN bookings AS b ON b.event_id = e.id
GROUP BY e.id, e.title, v.city, v.capacity, e.starts_at, e.price
ORDER BY e.starts_at;
Text
         title         |   city    |    local_start    | seats_sold | seats_left | revenue 
-----------------------+-----------+-------------------+------------+------------+---------
 Cupping Masterclass   | London    | 10 Nov 2026 18:00 |          9 |         31 |  405.00
 Latte Art Basics      | London    | 15 Jan 2027 18:00 |         38 |          2 |  950.00
 Tea & Mindfulness     | Pune      | 22 Jan 2027 10:00 |         11 |        109 |  165.00
 Home Roasting 101     | London    | 05 Feb 2027 18:00 |         10 |         30 |  350.00
 Singapore Coffee Fest | Singapore | 20 Feb 2027 11:00 |          7 |         53 |  280.00
(5 rows)

In a real system you’d store each venue’s time zone in a timezone column rather than a CASE — a good extension to try.

The busiest venues, by seats sold and fill rate across their events:

SQL
SELECT v.name,
       count(DISTINCT e.id)            AS events,
       sum(b.seats)                    AS seats_sold,
       round(100.0 * sum(b.seats) / (v.capacity * count(DISTINCT e.id)), 1) AS fill_rate_pct
FROM venues AS v
JOIN events AS e   ON e.venue_id = v.id
JOIN bookings AS b ON b.event_id = e.id
GROUP BY v.id, v.name, v.capacity
ORDER BY fill_rate_pct DESC;
Text
     name     | events | seats_sold | fill_rate_pct 
--------------+--------+------------+---------------
 The Roastery |      3 |         57 |          47.5
 Harbour Loft |      1 |          7 |          11.7
 Leaf Hall    |      1 |         11 |           9.2
(3 rows)

The best customers, ranked by spend with a window function:

SQL
SELECT a.name,
       count(*)                 AS bookings,
       sum(b.seats)             AS seats,
       sum(b.seats * e.price)   AS spent,
       rank() OVER (ORDER BY sum(b.seats * e.price) DESC) AS rank
FROM attendees AS a
JOIN bookings AS b ON b.attendee_id = a.id
JOIN events AS e   ON e.id = b.event_id
GROUP BY a.id, a.name
ORDER BY rank, a.name
LIMIT 5;
Text
     name     | bookings | seats | spent  | rank 
--------------+----------+-------+--------+------
 Ben Carter   |        3 |    18 | 590.00 |    1
 Elena García |        2 |    13 | 385.00 |    2
 Grace Kim    |        2 |     9 | 300.00 |    3
 Asha Rao     |        2 |    12 | 280.00 |    4
 Chen Wei     |        2 |     8 | 230.00 |    5
(5 rows)

Upcoming events with space left, as of 4 December 2026 — the query the website’s “book now” page would run:

SQL
SELECT e.title, v.capacity - COALESCE(sum(b.seats), 0) AS seats_left
FROM events AS e
JOIN venues AS v ON v.id = e.venue_id
LEFT JOIN bookings AS b ON b.event_id = e.id
WHERE e.starts_at >= '2026-12-04'
GROUP BY e.id, e.title, v.capacity
HAVING v.capacity - COALESCE(sum(b.seats), 0) > 0
ORDER BY e.starts_at;
Text
         title         | seats_left 
-----------------------+------------
 Latte Art Basics      |          2
 Tea & Mindfulness     |        109
 Home Roasting 101     |         30
 Singapore Coffee Fest |         53
(4 rows)

Step 4: booking without overbooking

Latte Art Basics has 40 seats and 38 are sold. If two people try to book at the same moment, a naive “check, then insert” lets both through — the oversold event from the brief. The safe approach, from Transactions:

  1. Lock the event row with SELECT … FOR UPDATE. A second booking for the same event now waits until the first transaction finishes, so they’re processed one at a time.
  2. Insert only if there’s room, with the capacity check in the same statement.
SQL
BEGIN;

SELECT id FROM events WHERE id = 2 FOR UPDATE;

INSERT INTO bookings (event_id, attendee_id, seats)
SELECT 2, 6, 2
WHERE (SELECT COALESCE(sum(seats), 0) FROM bookings WHERE event_id = 2) + 2
      <= (SELECT v.capacity FROM events AS e JOIN venues AS v ON v.id = e.venue_id WHERE e.id = 2)
RETURNING id, event_id, attendee_id, seats;

COMMIT;
Text
BEGIN
 id 
----
  2
(1 row)

 id | event_id | attendee_id | seats 
----+----------+-------------+-------
 18 |        2 |           6 |     2
(1 row)

INSERT 0 1
COMMIT

Hugo got the last two seats. Now Isha tries to book one more:

SQL
BEGIN;

SELECT id FROM events WHERE id = 2 FOR UPDATE;

INSERT INTO bookings (event_id, attendee_id, seats)
SELECT 2, 7, 1
WHERE (SELECT COALESCE(sum(seats), 0) FROM bookings WHERE event_id = 2) + 1
      <= (SELECT v.capacity FROM events AS e JOIN venues AS v ON v.id = e.venue_id WHERE e.id = 2)
RETURNING id, event_id, attendee_id, seats;

COMMIT;

SELECT count(*) AS bookings, sum(seats) AS seats FROM bookings WHERE event_id = 2;
Text
BEGIN
 id 
----
  2
(1 row)

 id | event_id | attendee_id | seats 
----+----------+-------------+-------
(0 rows)

INSERT 0 0
COMMIT
 bookings | seats 
----------+-------
        6 |    40
(1 row)

INSERT 0 0 — no row inserted, because the event is full. The application sees that nothing was returned and tells Isha the event is sold out. The total stays at exactly 40. Because every booking for an event locks that event’s row first, two simultaneous bookings can’t both see “2 seats left”: the second one waits, then sees the updated total. (In an application, this logic usually lives in a function in your code — or in a PL/pgSQL database function — running exactly these statements.)

Step 5: indexes

The reports and the booking check filter bookings by event_id, the customer report joins on attendee_id, and the website lists events by starts_at. Foreign keys aren’t indexed automatically, so add indexes for the real access paths:

SQL
CREATE INDEX bookings_event_id_idx    ON bookings (event_id);
CREATE INDEX bookings_attendee_id_idx ON bookings (attendee_id);
CREATE INDEX events_starts_at_idx     ON events (starts_at);
Text
CREATE INDEX
CREATE INDEX
CREATE INDEX

bookings (event_id, attendee_id) already has an index from its UNIQUE constraint — and since event_id is its first column, it could serve event lookups too; a separate event_id index is still a common, explicit choice. With a few rows, the planner will rightly prefer sequential scans; check what it would do on a big table with the technique from Query plans with EXPLAIN, by temporarily discouraging sequential scans:

SQL
BEGIN;
SET LOCAL enable_seqscan = off;
EXPLAIN (COSTS OFF)
SELECT sum(seats) FROM bookings WHERE event_id = 2;
ROLLBACK;
Text
BEGIN
SET
                        QUERY PLAN                        
----------------------------------------------------------
 Aggregate
   ->  Index Scan using bookings_event_id_idx on bookings
         Index Cond: (event_id = 2)
(3 rows)

ROLLBACK

(enable_seqscan = off is only a testing aid, never a production setting; SET LOCAL limits it to this transaction.)

Step 6: a reporting view

Finally, give marketing a safe, simple interface: a view with one row per event, and a read-only role that can use only the view:

SQL
CREATE VIEW event_sales AS
SELECT e.id    AS event_id,
       e.title,
       v.name  AS venue,
       e.starts_at,
       v.capacity,
       COALESCE(sum(b.seats), 0)              AS seats_sold,
       v.capacity - COALESCE(sum(b.seats), 0) AS seats_left,
       COALESCE(sum(b.seats), 0) * e.price    AS revenue
FROM events AS e
JOIN venues AS v ON v.id = e.venue_id
LEFT JOIN bookings AS b ON b.event_id = e.id
GROUP BY e.id, e.title, v.name, e.starts_at, v.capacity, e.price;

CREATE ROLE reporting;
GRANT SELECT ON event_sales TO reporting;

SET ROLE reporting;
SELECT title, seats_sold, seats_left, revenue FROM event_sales ORDER BY revenue DESC;
SELECT * FROM attendees;
RESET ROLE;
Text
CREATE VIEW
CREATE ROLE
GRANT
SET
         title         | seats_sold | seats_left | revenue 
-----------------------+------------+------------+---------
 Latte Art Basics      |         40 |          0 | 1000.00
 Cupping Masterclass   |          9 |         31 |  405.00
 Home Roasting 101     |         10 |         30 |  350.00
 Singapore Coffee Fest |          7 |         53 |  280.00
 Tea & Mindfulness     |         11 |        109 |  165.00
(5 rows)

ERROR:  permission denied for table attendees
RESET

Marketing gets the sales figures and nothing else — not attendees’ emails, and certainly not the ability to change bookings.

What you’ve built

In about a hundred lines of SQL you’ve designed a normalised schema, enforced its rules with constraints, loaded it, answered real business questions with joins, aggregates and window functions, made the most important write safe under concurrency, indexed it for its workload and published a secure reporting interface. That’s the full life cycle of a database — and the same steps apply whether it holds forty seats or forty million orders.

Ideas to extend it:

  • add a timezone column to venues and use it in every report;
  • add waiting lists: a waitlist table, and a query that offers freed seats in order;
  • add cancellations with a cancelled_at column, and make every report ignore cancelled bookings;
  • write a monthly cohort report of attendees by their first event;
  • load a few thousand generated bookings with generate_series and measure your indexes with EXPLAIN ANALYZE.

Congratulations on finishing SQL Fundamentals. You can now read, analyse, change and design relational databases with confidence — skills you’ll use in almost every technical role.

Exercise

Events that are nearly sold out

The starter builds a compact version of the project database. Create a view event_sales with one row per event: event_id, title, venue, capacity, seats_sold (0 if none) and seats_left. Then use the view to list the title, seats_sold, capacity and pct_sold (seats sold as a percentage of capacity, rounded to a whole number) of every event that is at least 75% sold, most sold first.

SQL
CREATE TABLE venues (
  id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name text NOT NULL UNIQUE,
  capacity integer NOT NULL CHECK (capacity > 0)
);
CREATE TABLE events (
  id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  venue_id integer NOT NULL REFERENCES venues (id),
  title text NOT NULL
);
CREATE TABLE bookings (
  id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  event_id integer NOT NULL REFERENCES events (id),
  seats integer NOT NULL CHECK (seats > 0)
);
INSERT INTO venues (name, capacity) VALUES ('The Roastery', 40), ('Leaf Hall', 120), ('Harbour Loft', 60);
INSERT INTO events (venue_id, title) VALUES
  (1, 'Latte Art Basics'), (2, 'Tea & Mindfulness'), (1, 'Home Roasting 101'), (3, 'Coffee Fest');
INSERT INTO bookings (event_id, seats) VALUES
  (1, 20), (1, 12), (1, 6), (2, 30), (2, 4), (3, 25), (3, 6), (4, 2);

-- the event_sales view, then the nearly-sold-out query

Summary

  • Start a database design from the business: the things (entities), their facts (columns) and how they relate (keys).
  • Put every rule you can into constraints — NOT NULL, UNIQUE, CHECK and foreign keys — so bad data can't get in.
  • Answer business questions with joins, LEFT JOINs for 'including zero', aggregates and window functions.
  • Protect limited resources with a transaction that locks the parent row (SELECT … FOR UPDATE) and only inserts if there is room.
  • Finish with indexes for the real queries and a view for shared reporting — the full life cycle of a database.