CHECK Constraint Cross Column Date Order

A CHECK constraint can compare several columns of the same row, rejecting bookings whose end time is not strictly after the start time at the database boundary.

SqlData Integrity

Code

snippet
-- A CHECK can reference multiple columns of the same row: cross-column invariants belong in the table definition
CREATE TABLE bookings (
    id        integer PRIMARY KEY,
    room      text NOT NULL,
    starts_at timestamptz NOT NULL,
    ends_at   timestamptz NOT NULL,
    -- The end must be strictly after the start: equal or inverted is rejected
    CONSTRAINT bookings_time_order CHECK (ends_at > starts_at),
    -- Bookings must last at least one minute
    CONSTRAINT bookings_min_duration
        CHECK (ends_at - starts_at >= interval '1 minute')
);

-- A valid interval inserts fine
INSERT INTO bookings VALUES (1, 'A', '2026-11-14 09:00+00', '2026-11-14 10:00+00');

-- Inverted interval: violates bookings_time_order, the whole INSERT fails
INSERT INTO bookings VALUES (2, 'A', '2026-11-14 10:00+00', '2026-11-14 09:00+00');

-- Only 30 seconds long: passes the first check, violates bookings_min_duration
INSERT INTO bookings VALUES (3, 'A', '2026-11-14 10:00+00', '2026-11-14 10:00:30+00');

What the code does

Several statements share this file — INSERT / CREATE, with bookings among the objects involved.

What the statements actually assemble: a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run it in the bookings database context.

Statements that matter

CREATE TABLE bookings (
id        integer PRIMARY KEY,
room      text NOT NULL,
starts_at timestamptz NOT NULL,
ends_at   timestamptz NOT NULL,
CONSTRAINT bookings_time_order CHECK (ends_at > starts_at),
CONSTRAINT bookings_min_duration
CHECK (ends_at - starts_at >= interval '1 minute')
);
INSERT INTO bookings VALUES (3, 'A', '2026-11-14 10:00+00', '2026-11-14 10:00:30+00');
INSERT INTO bookings VALUES (1, 'A', '2026-11-14 09:00+00', '2026-11-14 10:00+00');

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`bookings` — referenced directly, no join needed.