CHECK Cannot Aggregate Other Rows
Cross-row CHECK is implementation-dependent; the portable guard is a trigger that counts rows itself and must lock the zone first or inserts race past the cap.
Code
CREATE TABLE zone_seats (
seat_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
zone text NOT NULL,
reserved boolean NOT NULL DEFAULT false
);
-- 这类写法标准不保证:CHECK 表达式里不能跨行聚合
-- ALTER TABLE zone_seats
-- ADD CONSTRAINT too_few OPEN CHECK ((SELECT count(*) ...)); -- 语法错误
-- 跨行不变量要靠触发器自己数行数。注意并发:count-then-raise 是
-- check-then-insert,两个事务同时插入会读到同一个 count 而双双通过,
-- 上限会被突破——所以先对 zone 取事务级 advisory 锁,把并发插入
-- 串行化到同一把锁上,数到的行数才有保证。
CREATE OR REPLACE FUNCTION check_zone_cap()
RETURNS trigger AS $$
DECLARE
open_count integer;
BEGIN
PERFORM pg_advisory_xact_lock(hashtext(NEW.zone));
SELECT count(*) INTO open_count
FROM zone_seats
WHERE zone = NEW.zone AND reserved;
IF open_count >= 3 THEN
RAISE EXCEPTION 'zone % already has % reserved seats (cap 3)',
NEW.zone, open_count
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER zone_cap_check
BEFORE INSERT OR UPDATE OF zone, reserved ON zone_seats
FOR EACH ROW EXECUTE FUNCTION check_zone_cap();
-- 第四个预留触发异常;注释掉前三次插入即可反复演示
-- INSERT INTO zone_seats (zone, reserved) VALUES ('A', true);How the snippet works
SELECT / INSERT / UPDATE / CREATE statements share the script, touching open_count, zone_seats and of.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Run the statement against the open_count table.
Statements that matter
CREATE TRIGGER zone_cap_check
BEFORE INSERT OR UPDATE OF zone, reserved ON zone_seats
FOR EACH ROW EXECUTE FUNCTION check_zone_cap();
SELECT count(*) INTO open_count
FROM zone_seats
WHERE zone = NEW.zone AND reserved;
CREATE TABLE zone_seats (
seat_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
zone text NOT NULL,
reserved boolean NOT NULL DEFAULT false
);
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.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does this file reference?
- `open_count`, `zone_seats`, `of` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.