Check Constraints Reject Subqueries
CHECK constraints cannot contain subqueries or reference other rows, so cross-row rules need a deferrable constraint trigger that validates at commit time.
Code
-- 跨行规则不能写成 CHECK:表达式不允许包含子查询,也不能引用其他行
-- ERROR: cannot use subquery in check constraint
-- ALTER TABLE departments
-- ADD CONSTRAINT chk_budget
-- CHECK (budget <= (SELECT SUM(budget) FROM departments));
CREATE TABLE departments (id int PRIMARY KEY, budget numeric NOT NULL);
-- 替代做法:约束触发器,推迟到事务提交前统一校验
CREATE OR REPLACE FUNCTION check_total_budget() RETURNS trigger AS $$
BEGIN
IF (SELECT SUM(budget) FROM departments) > 1000000 THEN
RAISE EXCEPTION 'total budget exceeds cap';
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE CONSTRAINT TRIGGER trg_total_budget
AFTER INSERT OR UPDATE ON departments
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION check_total_budget();
-- 单行看没问题,提交前总额超限才报错:
-- BEGIN;
-- INSERT INTO departments VALUES (1, 600000), (2, 500000);
-- COMMIT; -- ERROR: total budget exceeds cap(总额 1100000 超上限)How the snippet works
Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with departments and on among the objects involved.
What the statements actually assemble: SUM aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Using it
Run it in the departments database context.
Key statements
CREATE CONSTRAINT TRIGGER trg_total_budget
AFTER INSERT OR UPDATE ON departments
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION check_total_budget();
CREATE OR REPLACE FUNCTION check_total_budget() RETURNS trigger AS $$
BEGIN
IF (SELECT SUM(budget) FROM departments) > 1000000 THEN
RAISE EXCEPTION 'total budget exceeds cap';
CREATE TABLE departments (id int PRIMARY KEY, budget numeric NOT NULL);
Interactive Tools for This Topic
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.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.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?
- The references are `departments`, `on`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.