← 中文资源

简体中文版本

CHECK 约束在 UPDATE 时同样生效

CHECK 约束不只看 INSERT:INSERT 时通过的行,UPDATE 成非法值会被同一约束拦下;修复方向是把列改回合法值,而不是拆约束。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / UPDATE / CREATE 语句,涉及 subscription。 真正干活的子句:WHERE 决定这条语句会作用到哪些行;CHECK 约束在写入时就把越界值拒之门外;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

这里用到哪些关系?

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

核心语句

SELECT user_id, seats FROM subscription WHERE user_id = 1;
UPDATE subscription SET seats = 2 WHERE user_id = 1;
CREATE TABLE subscription (
    user_id    int PRIMARY KEY,
    seats      int NOT NULL CHECK (seats >= 1),
    expires_on date NOT NULL CHECK (expires_on > DATE '2020-01-01')
);

代码示例

-- CHECK constraints fire on INSERT and UPDATE alike: a row that
-- inserted cleanly can still fail the moment an UPDATE bends it out of range
CREATE TABLE subscription (
    user_id    int PRIMARY KEY,
    seats      int NOT NULL CHECK (seats >= 1),
    expires_on date NOT NULL CHECK (expires_on > DATE '2020-01-01')
);

INSERT INTO subscription VALUES (1, 5, DATE '2026-12-01');   -- satisfies the constraint on both sides

-- a row accepted on INSERT is stopped by the same constraint when UPDATE sets an invalid value:
-- UPDATE subscription SET seats = 0 WHERE user_id = 1;
--   -> ERROR: new row for relation "subscription" violates check constraint "subscription_seats_check"

-- the fix is to bring the column back to a valid value, not to drop the constraint
UPDATE subscription SET seats = 2 WHERE user_id = 1;
SELECT user_id, seats FROM subscription WHERE user_id = 1;