How to enforce status transitions in SQL: guarded updates, transition tables and timestamps per state

254 status columns in our schema gallery, zero transition tables. How to stop illegal status changes with guarded updates, CHECKs, triggers and history.

· 7 min read · drawDB team

Put the from-state in the WHERE clause of every status change: UPDATE trips SET status = 'in_progress', started_at = now() WHERE id = 42 AND status = 'waiting', then check that one row changed. That single statement rejects an illegal jump and settles the race between two requests that both read waiting, and it works the same way in PostgreSQL, MySQL, SQLite, SQL Server and Oracle. Add CHECK constraints that tie each state to its timestamp. Add a transition table and a trigger only when code you don't control writes to the table, and an append-only history table when a state can be entered more than once.

We looked at how the 100 schemas in the drawDB gallery handle this. 75 of them have a status column, 254 columns in all, and their notes document 1,156 states between them. Not one schema has a table of allowed transitions. 107 of the 254 status columns (42%) have a timestamp column for at least one of their states, such as delivered_at next to delivered. Four tables keep a history of status changes, as intervals or as lifecycle events. The rules live in prose: the Uber trip's status note ends with "Only ever moves forward," and nothing in the DDL makes that true.

TechniqueStops an illegal jumpStops two concurrent winnersHolds for ad-hoc SQLDialects
Guarded UPDATE ... WHERE status = 'from'Yes, if every writer uses itYesNoAll
CHECK tying states to timestampsPartly: a state can't skip its dataNoYesAll, with a MySQL caveat
Transition table + triggerYesTogether with the guarded UPDATEYesPostgreSQL, MySQL, MariaDB, SQLite, SQL Server, Oracle
previous_status + composite foreign keyOnly for writers that set it honestlyNoNoAll
Append-only history tableNo, it recordsNoOnly if a trigger writes itAll

What does a status lifecycle look like in a real schema?

The ride-hailing schema has the cleanest example. A trip moves accepted → arriving → waiting → in_progress → completed, and can be cancelled by either side before the rider gets in. Each state that matters has its own timestamp column: accepted_at, arrived_at, started_at, ended_at, cancelled_at.

That shape is common in the gallery. The DoorDash delivery schema has six of its seven order states mirrored as timestamps, from placed_at to delivered_at, because the timestamps make "every operational metric a subtraction instead of a scan of an event log". Crypto withdrawals, email sends and grocery orders follow the same pattern. Lifecycles are short: the 253 documented sets have a median of four states.

The value set is the easy half, and our enum vs lookup table post covers it: a varchar with a named CHECK. This post covers the other half: which moves between those values are allowed, and what the row has to look like after each one.

How do you stop an illegal status transition?

Make the expected current state part of the update. The application decides that a trip can start, then writes:

PostgreSQL
UPDATE trips
SET status = 'in_progress', started_at = now()
WHERE id = 42 AND status = 'waiting'
RETURNING id;

If the trip isn't waiting any more, no row matches and RETURNING comes back empty. The application treats zero rows as "someone got there first" and reloads, instead of overwriting. A move with several legal sources lists them:

PostgreSQL
UPDATE trips
SET status = 'cancelled_by_rider', cancelled_at = now()
WHERE id = 42 AND status IN ('accepted', 'arriving', 'waiting')
RETURNING id;

Compare that with the usual ORM flow: load the trip, check trip.status == 'waiting' in memory, set the new status, save. Between the load and the save, the rider can cancel. Both requests pass the check, and the last save wins, leaving a cancelled trip with a running meter.

The guarded UPDATE closes that gap because of how row locks work. In PostgreSQL's default Read Committed level, the second UPDATE waits for the first to commit, then re-evaluates its WHERE clause against the new version of the row. The status is now cancelled_by_rider, the condition fails, and zero rows change. Under Repeatable Read it fails with a serialization error instead, which you retry. MySQL's InnoDB does the same: an UPDATE reads the latest committed row, not the transaction's snapshot. In MySQL, read the count with ROW_COUNT() or your driver's affected-rows value. In SQL Server it's @@ROWCOUNT.

The guard is a convention, though. It protects you only as long as every code path writes the from-state, and a support engineer running UPDATE trips SET status = 'completed' WHERE id = 42 from a console skips it.

How do you tie each state to its timestamp?

With CHECK constraints that relate the status to the rest of the row. They can't see the old value, so they can't forbid a jump, but they make each state carry its own evidence. A completed trip without ended_at can't exist, and neither can a cancelled trip with a start time:

PostgreSQL
CREATE TABLE trips (
  id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  status varchar(32) NOT NULL DEFAULT 'accepted',
  accepted_at timestamptz NOT NULL DEFAULT now(),
  arrived_at timestamptz,
  started_at timestamptz,
  ended_at timestamptz,
  cancelled_at timestamptz,
  CONSTRAINT trips_status_check CHECK (status IN (
    'accepted', 'arriving', 'waiting', 'in_progress', 'completed',
    'cancelled_by_rider', 'cancelled_by_driver')),
  CONSTRAINT trips_arrived_check
    CHECK (status NOT IN ('waiting', 'in_progress', 'completed') OR arrived_at IS NOT NULL),
  CONSTRAINT trips_started_check
    CHECK ((status IN ('in_progress', 'completed')) = (started_at IS NOT NULL)),
  CONSTRAINT trips_ended_check
    CHECK ((status = 'completed') = (ended_at IS NOT NULL)),
  CONSTRAINT trips_cancelled_check
    CHECK ((status IN ('cancelled_by_rider', 'cancelled_by_driver')) = (cancelled_at IS NOT NULL)),
  CONSTRAINT trips_time_order_check
    CHECK (arrived_at >= accepted_at AND started_at >= arrived_at AND ended_at >= started_at)
);

The equality form (status = 'completed') = (ended_at IS NOT NULL) says both directions at once: completed trips have an end time, and nothing else does. trips_arrived_check is one-way because a rider can cancel after the driver arrives. The time-order constraint relies on a detail of CHECK: a NULL result passes, so started_at >= arrived_at only bites once both are set.

Run the console shortcut from earlier against this table and PostgreSQL refuses it with new row for relation "trips" violates check constraint "trips_ended_check", because the shortcut didn't set ended_at. Writers who want to skip a state now have to fabricate its data as well. That doesn't make a skip impossible, but it does make it deliberate.

Write these as table constraints in MySQL. A CHECK written inside a column definition may only mention that column, and MySQL 8.4 rejects anything else with error 3813, Column check constraint '...' references other column (docs). PostgreSQL and MariaDB accept the same column constraint even though its docs say it "should" reference only its own column.

When do you need a transition table and a trigger?

When something other than your own code writes the status: a second service, a data fix run by hand, an admin tool built on the ORM. Then the allowed moves have to live where every write passes, which means a table of legal pairs and a trigger that checks it:

PostgreSQL
CREATE TABLE trip_transitions (
  from_status varchar(32) NOT NULL,
  to_status varchar(32) NOT NULL,
  PRIMARY KEY (from_status, to_status)
);

INSERT INTO trip_transitions (from_status, to_status) VALUES
  ('accepted', 'arriving'),
  ('arriving', 'waiting'),
  ('waiting', 'in_progress'),
  ('in_progress', 'completed'),
  ('accepted', 'cancelled_by_rider'), ('accepted', 'cancelled_by_driver'),
  ('arriving', 'cancelled_by_rider'), ('arriving', 'cancelled_by_driver'),
  ('waiting', 'cancelled_by_rider'), ('waiting', 'cancelled_by_driver');

CREATE FUNCTION trips_check_transition() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM trip_transitions
    WHERE from_status = OLD.status AND to_status = NEW.status
  ) THEN
    RAISE EXCEPTION 'illegal trip transition: % -> %', OLD.status, NEW.status
      USING ERRCODE = 'check_violation';
  END IF;
  RETURN NEW;
END;
$$;

CREATE TRIGGER trips_transition
  BEFORE UPDATE OF status ON trips
  FOR EACH ROW
  WHEN (OLD.status IS DISTINCT FROM NEW.status)
  EXECUTE FUNCTION trips_check_transition();

An attempt to go straight from accepted to in_progress now fails with illegal trip transition: accepted -> in_progress, whoever sends it. The WHEN clause skips updates that don't change the status, so editing a trip's fare doesn't touch the transition table. The same trigger in MySQL, wrapped in DELIMITER when you run it from the mysql client:

MySQL
CREATE TRIGGER trips_transition
BEFORE UPDATE ON trips
FOR EACH ROW
BEGIN
  IF NEW.status <> OLD.status AND NOT EXISTS (
    SELECT 1 FROM trip_transitions
    WHERE from_status = OLD.status AND to_status = NEW.status
  ) THEN
    SIGNAL SQLSTATE '45000'
      SET MESSAGE_TEXT = 'illegal trip transition';
  END IF;
END

The trigger doesn't replace the guarded UPDATE. It rejects moves that are illegal in general, but two cancellations of a waiting trip are each legal on their own. Keep the from-state in the WHERE clause for the race, and use the trigger for the graph.

The transition table also pays off when the graph is data rather than code. A CRM where each team defines its own pipeline stages, or a helpdesk with per-customer workflows, needs rows it can edit without a deploy. For a fixed lifecycle like a ride, a CASE in the trigger function works just as well and saves a lookup. We'd still keep the table, because it doubles as documentation you can query.

Can a foreign key enforce transitions without a trigger?

Only partly. The trick, described by Joe Celko in State Transition Constraints, stores the previous status on the row and points a composite foreign key at the transition table:

PostgreSQL
ALTER TABLE trips ADD COLUMN previous_status varchar(32);

ALTER TABLE trips ADD CONSTRAINT trips_transition_fk
  FOREIGN KEY (previous_status, status)
  REFERENCES trip_transitions (from_status, to_status);

UPDATE trips
SET previous_status = status, status = 'arriving'
WHERE id = 42 AND status = 'accepted';

It works with no procedural code, and it forces writers to name both ends of every move. We tested three ways around it in PostgreSQL 16, and all three got through:

  • Lying about the source. SET previous_status = 'waiting', status = 'in_progress' on a trip that was arriving passes, because (waiting, in_progress) is a legal pair. The key checks the pair you claim, not the row you replaced.
  • A null previous status. Composite foreign keys use MATCH SIMPLE by default, so if either column is NULL, the constraint isn't checked at all. SET previous_status = NULL, status = 'completed' goes through, and so does an INSERT that starts a trip as completed.
  • Assignment order in MySQL. PostgreSQL evaluates every SET expression against the old row. MySQL evaluates single-table assignments left to right, so SET status = 'waiting', previous_status = status stores waiting in both columns. Put previous_status = status first in MySQL.

The foreign key checks the writer's honesty, not the move itself. Only a trigger can see OLD. Use the composite key if you can't use triggers at all, and say in the column note what it doesn't guarantee.

Where should status history go?

On the row, as one timestamp per state, when the lifecycle only moves forward. The Uber schema's note on trips gives the reason: one row answers how long the rider waited, how long the driver waited and how long the ride took, with no join. That holds as long as each state is entered at most once.

When a state can recur (paused and running, an issue that reopens, a deal that moves back a stage), a paused_at column only remembers the last pause. Then the history needs rows of its own. The CRM pipeline schema keeps deal_stage_history with from_stage_id, to_stage_id, entered_at and exited_at, which is where stage conversion rates and time in stage come from:

In PostgreSQL, write the history row in the same statement as the guarded update, so a lost race writes nothing:

PostgreSQL
CREATE TABLE trip_status_history (
  id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  trip_id bigint NOT NULL REFERENCES trips (id) ON DELETE CASCADE,
  from_status varchar(32),
  to_status varchar(32) NOT NULL,
  changed_at timestamptz NOT NULL DEFAULT now(),
  changed_by bigint
);

CREATE INDEX trip_status_history_trip_idx ON trip_status_history (trip_id, changed_at);

WITH moved AS (
  UPDATE trips
  SET status = 'in_progress', started_at = now()
  WHERE id = 42 AND status = 'waiting'
  RETURNING id, status
)
INSERT INTO trip_status_history (trip_id, from_status, to_status)
SELECT id, 'waiting', status FROM moved;

If the UPDATE matches nothing, moved is empty and the INSERT adds nothing. In MySQL, run the two statements in one transaction and skip the insert when ROW_COUNT() is zero. If ad-hoc writes must be recorded too, move the insert into the transition trigger as an AFTER UPDATE. The table then logs every change whoever made it, at the cost of not knowing changed_by unless the session sets it.

What does drawDB export for these constraints?

Each column in the editor has a Check expression field, and every exporter writes it inline after the column, as CHECK(...). A check that only mentions its own column, like the status value set, exports cleanly to all six databases. A check that relates the status to a timestamp exports and runs on PostgreSQL and MariaDB. On MySQL, though, the inline placement triggers the "references other column" error, so add those as table constraints in your migration. drawDB doesn't model triggers, so the transition trigger and the history insert belong in the migration too. Model trip_transitions and trip_status_history as ordinary tables in the diagram, and they export with their keys.

To try it, open the ride-hailing schema in the editor, add the status value check to trips.status, export the SQL for your database, and paste in the timestamp checks and the trigger from this post. If you haven't settled how to store the value set itself, start with enum, lookup table or CHECK constraint.

Frequently asked questions

Should state transitions be enforced in the database or in the application?

Both, with different jobs. The application owns the rules for when a move is allowed (the rider is in the car, the payment cleared), and expresses the from-state in a guarded UPDATE so concurrent requests cannot both win. The database owns the facts that must hold whoever writes: the value set as a CHECK, each state's timestamp as a CHECK, and, when other services or people run SQL against the table, the transition graph as a trigger.

Is SELECT ... FOR UPDATE better than a guarded UPDATE?

Only when the decision needs data the UPDATE cannot see in its WHERE clause, such as calling a payment provider or reading several other tables before choosing the next state. Then lock the row with SELECT ... FOR UPDATE, decide, and write in the same transaction. For a plain move from one state to another, the guarded UPDATE does the same job in one round trip and holds the row lock for less time.

How do I model a state that can be entered more than once, like paused and running?

Keep the current status on the row and move the timestamps into an append-only history table with from_status, to_status and changed_at. A column like paused_at only remembers the last pause, so total paused time and the number of pauses are lost. One column per state works when the lifecycle only moves forward, as a ride or a delivery does.

How do I find rows stuck in a state for too long?

Filter on the status and the timestamp of entering it, and back the query with a partial index in PostgreSQL, for example CREATE INDEX ON trips (accepted_at) WHERE status IN ('accepted', 'arriving', 'waiting'). The index only holds open rows, so it stays small while completed rows pile up. MySQL has no partial indexes; use a composite index on (status, accepted_at) instead.

Can I derive the status from the timestamps instead of storing it?

Yes, when the states are strictly ordered. In PostgreSQL a stored generated column such as status text GENERATED ALWAYS AS (CASE WHEN read_at IS NOT NULL THEN 'read' WHEN delivered_at IS NOT NULL THEN 'delivered' ELSE 'sent' END) STORED can never disagree with the timestamps, and you can index it. It stops working as soon as two states can be left in either order or a state has no timestamp of its own.