Why this matters
Adding a `CHECK` or foreign-key constraint without `NOT VALID` validates every existing row inside an `ACCESS EXCLUSIVE` lock — fine on small tables, an outage on large ones. The two-step pattern (add `NOT VALID`, then `VALIDATE CONSTRAINT` in a separate transaction) holds only a `SHARE UPDATE EXCLUSIVE` lock during validation. `PRIMARY KEY`, `UNIQUE`, and `NOT NULL` are out of scope (they don't accept `NOT VALID`).
Examples
Incorrect
ALTER TABLE t ADD CONSTRAINT c_check CHECK (x > 0);ALTER TABLE t ADD CONSTRAINT c_fk FOREIGN KEY (other_id) REFERENCES other(id);Correct
ALTER TABLE t ADD CONSTRAINT c_check CHECK (x > 0) NOT VALID;ALTER TABLE t ADD CONSTRAINT c_fk FOREIGN KEY (other_id) REFERENCES other(id) NOT VALID;Configure it
// eslint.config.js
import postgresql from "eslint-plugin-postgresql";
export default [
{
files: ["**/*.sql"],
languageOptions: {
parser: postgresql.configs.recommended.languageOptions.parser,
},
plugins: { postgresql },
rules: {
"postgresql/prefer-add-constraint-not-valid": "warn",
},
},
]; Options
Edit the SQL — only prefer-add-constraint-not-valid is enabled.
Pre-filled with the first incorrect example. Toggle off in the rule shelf to see how the diagnostic disappears.
Diagnostics
No issues found.
2 rules enabled.
Rule under test
prefer-add-constraint-not-valid — plus no-syntax-error as a safety net.