All rules

Safety

postgresql/consistent-fk-not-valid

Enforce a consistent stance on `NOT VALID` for `ALTER TABLE ... ADD FOREIGN KEY`.

  • Type problem
  • Recommended warn
  • Fixable no

Why this matters

Adding a foreign key normally validates every existing row under an `ACCESS EXCLUSIVE` lock that blocks writers. The safe pattern is to `ADD ... NOT VALID` (metadata-only) and then `VALIDATE CONSTRAINT` in a separate migration; `VALIDATE` only takes a `SHARE UPDATE EXCLUSIVE` lock. Some projects prefer the inverse — fail loudly at constraint-add time — and can flip this rule with the `style` option.

Examples

Incorrect

Incorrect
ALTER TABLE orders
  ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers (id);

Correct

Correct
ALTER TABLE orders
  ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;
Correct
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;

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/consistent-fk-not-valid": [
        "warn",
        {
          style: "always",
        },
      ],
    },
  },
];

Options

style "always" | "never" default: "always"
`always` (default) requires `NOT VALID` on `ADD CONSTRAINT ... FOREIGN KEY`. `never` forbids it — useful for projects that want the constraint to immediately reject existing violations rather than waiting on a follow-up `VALIDATE CONSTRAINT`.
Try this rule

Edit the SQL — only consistent-fk-not-valid is enabled.

Pre-filled with the first incorrect example. Toggle off in the rule shelf to see how the diagnostic disappears.

0 errors 0 warnings parse 0ms · rules 0ms
Diagnostics

No issues found.

2 rules enabled.

Rule under test consistent-fk-not-valid — plus no-syntax-error as a safety net.
eslint-plugin-postgresql

An ESLint plugin that lints .sql files with real PostgreSQL grammar and a curated set of best-practice rules.

© 2026 eslint-plugin-postgresql contributors Built on libpg-query · PostgreSQL 17