Roll Out PostgreSQL CHECK Constraints with Legacy Data and Concurrent Writes

Roll Out PostgreSQL CHECK Constraints with Legacy Data and Concurrent Writes

Adding a rule that requires amounts to be non-NULL and nonnegative to a live business table presents a sequencing problem. Adding the CHECK constraint directly may fail because of invalid legacy data; cleaning the data first leaves a window for new invalid values to slip in. PostgreSQL’s NOT VALID lets you protect new writes first, repair existing rows next, and validate the constraint last. The following lab checks each of these three stages using an isolated test table on a dedicated server.

Define the Lab Boundaries

Use an existing PostgreSQL installation and psql, with a test database where you have permission to create tables. Open two sessions connected to the same database, both using autocommit. Do not wrap an entire sequence of commands in a transaction except where a transaction is explicitly shown. Supply connection parameters for your environment without changing the database’s external listening configuration.

First check the connection target, then create a dedicated schema. If the name already exists, stop and choose another lab name rather than overwriting existing objects.

SELECT current_database(), current_user, version();

CREATE SCHEMA check_lab;

CREATE TABLE check_lab.orders (
    row_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    amount_cents bigint,
    note text NOT NULL DEFAULT ''
);

INSERT INTO check_lab.orders (amount_cents)
VALUES (100), (-20), (NULL);

Amounts are stored as integer cents to keep floating-point rounding out of the constraint test. The three rows represent a valid amount, a negative amount, and a missing value. These are synthetic test fixtures, not business data.

NOT VALID does not disable enforcement. It only postpones the full scan of existing rows. Once the constraint has been added successfully, rows produced by new inserts or updates must satisfy it.

Before rolling this out, also check application error handling: a CHECK constraint violation normally returns SQLSTATE 23514. The application should recognize it as an input or state conflict, rather than retrying the same invalid request indefinitely.

Protect New Writes First

Explicitly Reject NULL Values

CHECK (amount_cents >= 0) alone does not reject NULL values: a row can still pass when the check expression evaluates to unknown. Include an explicit non-NULL condition:

SET lock_timeout = '2s';
SET statement_timeout = '30s';

ALTER TABLE check_lab.orders
ADD CONSTRAINT amount_valid
CHECK (amount_cents IS NOT NULL AND amount_cents >= 0)
NOT VALID;

These two timeouts are safeguards for the lab, not recommended production settings. Adding the constraint still requires a strong table-level lock. NOT VALID avoids scanning historical data at this stage; it does not eliminate lock waits. On busy tables, check for long-running transactions. If the operation times out, investigate the blocker rather than repeatedly resubmitting the change.

Run the following two statements separately. Both should be rejected by amount_valid:

INSERT INTO check_lab.orders (amount_cents) VALUES (-1);

INSERT INTO check_lab.orders (amount_cents) VALUES (NULL);

If your script is configured to stop on error, run these two expected failures as separate invocations and check both the error code and the constraint name. Do not treat every nonzero exit status as a successful test: connection failures and insufficient privileges also cause errors.

Next, insert a valid value to confirm that writes are not being blocked indiscriminately:

INSERT INTO check_lab.orders (amount_cents) VALUES (250);

Check the Update Path

Run the following with autocommit enabled:

UPDATE check_lab.orders
SET note = 'reviewed'
WHERE row_id = 2;

Even though only the note changes, the updated row still contains a negative amount, so the statement should fail. The rollout therefore affects more than new orders: ordinary edits to invalid legacy rows may also start returning errors. Include these application paths in pre-release testing.

Repair Historical Data

First attempt validation. It should fail because of the invalid legacy rows:

ALTER TABLE check_lab.orders
VALIDATE CONSTRAINT amount_valid;

Failure does not automatically remove the constraint or disable protection for new writes. Next, query the rows that need repair:

SELECT row_id, amount_cents
FROM check_lab.orders
WHERE amount_cents IS NULL OR amount_cents < 0
ORDER BY row_id;

Do not simply replace negative production values with zero. They may represent refunds, reversals, or bad imports. If negative amounts are legitimate, the problem is the rule, not the data. Establish the business meaning first, then choose whether to correct the data, migrate it, or redesign the condition.

For this lab, explicitly correct the second row to 200 cents and the third row to zero:

BEGIN;

UPDATE check_lab.orders
SET amount_cents = 200
WHERE row_id = 2 AND amount_cents = -20;

UPDATE check_lab.orders
SET amount_cents = 0
WHERE row_id = 3 AND amount_cents IS NULL;

COMMIT;

Check that each update affects exactly one row, then rerun the invalid-row query. It should return zero rows. In production, commit repairs in batches, record the primary keys and the basis for each correction, and monitor transaction logs, replication lag, and free disk space. Do not wrap the entire historical cleanup in one large transaction.

A query returning no invalid rows is not yet definitive proof. It describes only the data visible to that particular query. The database must still perform formal validation in the next step.

Verify with Two Sessions

In session A, begin a transaction and write a valid amount, but do not commit yet:

BEGIN;

UPDATE check_lab.orders
SET amount_cents = 151
WHERE row_id = 1;

Switch to session B, set protective timeouts, and run validation:

SET lock_timeout = '2s';
SET statement_timeout = '30s';

ALTER TABLE check_lab.orders
VALIDATE CONSTRAINT amount_valid;

In this isolated lab, validation should complete without waiting for A’s ordinary update to commit. The SHARE UPDATE EXCLUSIVE lock acquired by validation is compatible with the ROW EXCLUSIVE lock used by ordinary writes. New row versions produced by concurrent writes are also protected by the constraint that is already being enforced.

Validation still scans the table and consumes I/O. It may also wait for other, incompatible locks, so this result must not be generalized to mean that validation can never block. If B times out, first check for additional sessions or schema changes rather than simply increasing the timeout.

Return to A and undo the test update:

ROLLBACK;

Rolling back A only undoes that transaction’s data changes; it does not undo the validation already committed by B. Next, check the catalog state in B:

SELECT conname, convalidated
FROM pg_constraint
WHERE conrelid = 'check_lab.orders'::regclass
  AND conname = 'amount_valid';

Expect exactly one row with convalidated set to true. If no row is returned, check the database, schema, and constraint name. An empty result does not mean validation passed.

Retain Rollout Evidence

After validation, test a negative write and a NULL write separately once more, confirming that the same constraint still rejects both. Then write a valid value to confirm that the normal path remains available. Save the constraint definition, error code, number of repaired rows, validation status, and execution time as a reviewable change record.

Rollback planning must distinguish two actions: rolling back the cleanup transaction can undo data changes that have not yet been committed; dropping the constraint only removes protection and does not restore historical data changes that have already been committed. If validation fails, the usual response should be to keep the constraint in place while investigating, rather than immediately removing the safeguard.

Once the lab objects are no longer needed and both sessions have ended their transactions, remove the dedicated schema:

DROP SCHEMA check_lab CASCADE;

Final acceptance requires all four conditions to hold: invalid legacy rows have been addressed, new invalid writes are rejected, valid writes still succeed, and the catalog reports the constraint as validated. Only when all four are true can “the command succeeded” be considered “the constraint rollout is complete.”

Frequently asked questions

Does NOT VALID mean the constraint is inactive?

No. Once the constraint is added successfully, new INSERT and UPDATE operations must satisfy it. NOT VALID only postpones checking existing rows; updating an invalid legacy row can also fail.

Does VALIDATE CONSTRAINT block ordinary writes?

Validation takes a SHARE UPDATE EXCLUSIVE lock, which is compatible with the ROW EXCLUSIVE lock used by ordinary writes. It still scans the table and may wait for conflicting schema changes or other incompatible lock holders.

AMD EPYC 7543P Dedicated Server

From $446/month

Configure a Dedicated Server

Choose memory, storage, bandwidth, and OS to suit the workload. The configuration page shows the amount due for the current billing period.