← 中文资源

简体中文版本

借助已验证 CHECK 快速 SET NOT NULL

先挂 NOT VALID 的 CHECK 并 VALIDATE,再执行 SET NOT NULL:优化器借已验证约束跳过全表扫描,长锁操作变成瞬时元数据变更(PostgreSQL 12+)。

阅读英文原文

实现说明

这个文件依次执行 ALTER 语句。 逐子句看,这些语句使用了:CHECK 约束在写入时就把越界值拒之门外;必填列上的 NOT NULL 限定。

核心语句

ALTER TABLE profiles ADD CONSTRAINT profiles_email_required
    CHECK (email IS NOT NULL)
    NOT VALID;
ALTER TABLE profiles VALIDATE CONSTRAINT profiles_email_required;
ALTER TABLE profiles DROP CONSTRAINT profiles_email_required;

代码示例

-- Goal: make email NOT NULL on a table already holding millions of rows,
-- a direct ALTER COLUMN SET NOT NULL scans the whole table under a long-held lock.
-- The PG 12+ way: attach a NOT VALID CHECK declaring the same fact first
ALTER TABLE profiles ADD CONSTRAINT profiles_email_required
    CHECK (email IS NOT NULL)
    NOT VALID;

-- VALIDATE CONSTRAINT takes only a shared lock to verify existing rows, with reads and writes allowed throughout
ALTER TABLE profiles VALIDATE CONSTRAINT profiles_email_required;

-- The planner already knows email has no NULLs: SET NOT NULL skips the table scan and completes instantly
ALTER TABLE profiles ALTER COLUMN email SET NOT NULL;

-- Once the CHECK has served its purpose, drop it; the NOT NULL stands on its own
ALTER TABLE profiles DROP CONSTRAINT profiles_email_required;