← 中文资源

简体中文版本

CHECK 约束校验跨列日期顺序

CHECK 可以引用同一行的多个列:结束时间必须晚于开始时间这类不变量下沉到建表语句,非法区间在数据库边界就被拒绝,不用等应用层 bug。

阅读英文原文

实现说明

这个文件依次执行 INSERT / CREATE 语句,涉及 bookings。 具体组合了这些手段:CHECK 约束在写入时就把越界值拒之门外;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

这段 SQL 会碰到哪些对象?

bookings——直接引用,无需连接。

核心语句

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');
INSERT INTO bookings VALUES (2, 'A', '2026-11-14 10:00+00', '2026-11-14 09:00+00');

代码示例

-- 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');