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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.
FAQ
- Which objects does the SQL touch?
- `bookings` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.