实现说明
这个文件依次执行 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');