Use PostgreSQL CHECK ... NOT VALID to enforce a new row rule as soon as all active writers can obey it. The add operation skips the validation scan of existing rows. After the add commits, PostgreSQL enforces the rule on new and updated rows. Repair historical exceptions from authoritative evidence, then validate and confirm the catalog state before allowing readers to assume every row obeys the rule. If the rule depends on another row or an external system, choose an enforcement design that covers that dependency.
TL;DR. Treat writer readiness, enforcement, historical correction, and validation as four separate milestones. Leave an intentional old exception in staging, prove that a new invalid write is blocked and the first validation fails, correct the fixture, and verify that the named constraint becomes valid. Keep readers on their existing exception policy until that final state is visible.
Key decision facts
| Decision | What PostgreSQL provides | What your rollout must prove |
|---|---|---|
| Block new invalid review records | A staged CHECK is enforced when the add commits | Real deployed writer paths can still complete valid work |
| Keep historical exceptions temporarily | NOT VALID skips a scan at add time | The exception ledger has scope, owners, and a supported repair path |
| Reduce disruption during the scan | VALIDATE CONSTRAINT uses a lighter lock than the ordinary add | The installed version and concurrent operations fit the maintenance window |
| Switch readers to a stronger assumption | The catalog records whether validation succeeded | The exact relation, named rule, observed data, and reader behavior agree |
Define a row rule the database can actually enforce
Begin with a business decision expressed as a testable predicate. In the example, an AI-assisted document review may enter the approved state only when the review record holds an attributable reviewer ID. A pending record may exist before anyone takes ownership. The rule applies to a row's current state. It leaves several facts to other controls. A reviewer ID can be present even if the referenced reviewer lacks permission for that decision. A record can be marked approved with a valid reviewer ID while its associated document revision has changed. If your users need those stronger facts, list them separately and identify the place that can observe them.
Write the intended behavior for every combination the row can represent. Suppose review_status has a separate non-null rule and a fixed set of states in this schema. Then an approved row with no reviewer must fail and a pending row with no reviewer must pass this check. An approved row with a reviewer passes the presence test, subject to any other constraints on the row. An unknown status is rejected by its existing state rule. Keeping those rules distinct makes a failed write explainable. A test that only asserts that some error occurred can misread an unrelated status rejection as evidence that the new reviewer rule works.
Pay particular attention to null. PostgreSQL treats a CHECK expression that evaluates to true or null as satisfied. An expression such as review_status <> 'approved' OR reviewer_id > 0 can accept an approved record if its reviewer is null. For presence, test explicitly with reviewer_id IS NOT NULL. If the status itself may be null, write down whether that represents an incomplete row, a legacy state, or an invalid row. The example deliberately relies on a separate state requirement. Check that requirement in the exact database and through the writer before adopting the example. PostgreSQL CHECK constraint semantics
Keep the predicate tied to the row. A CHECK that calls a function to interpret current policy or consult another table can appear to test a richer business rule. PostgreSQL documents assumptions about immutability of CHECK conditions and does not support CHECK constraints that reference table data other than the new or updated row. A later policy edit would otherwise change the intended meaning of old rows without running the new check on all of them. Use database constraints designed for the relationship where applicable, or enforce a separate operation and retain a corresponding record of what was checked. A required reviewer reference may need a foreign key. Authorization for that review still needs a control that can see the user's current authority and the intended document.
Test the choice with a small truth table agreed by the people who own the data. Ask the review lead what a historical approval with a missing reviewer actually means. The answer could be an incomplete audit import, a real approval with a recoverable link, or a classification error. These histories produce the same null. They require different remediation, and a constraint alone cannot tell them apart. The data repair plan should preserve that ambiguity until evidence supports the correction.
Map every active writer to the new invariant
List writers by behavior, including those that rarely run. The main admin interface may attach a reviewer immediately while a worker imports legacy rows and fills approval attribution later. A restore or replay job may recreate a historical state using old field names. A bulk import, periodic task, migration, or manual back-office edit can touch the table without going through the product code just tested. Record which writers insert approved rows, which transition existing rows to approved, and which only update supposedly unrelated fields.
An unrelated update matters because PostgreSQL checks updated rows after the constraint has been installed. A note editor can fail while editing a historical approved row with no reviewer. The author of that note may have no authority or information to fix the reviewer ID. Decide how to handle these exceptions before the add. Options in a real rollout include repairing the small subset most likely to receive active edits, taking those cases out of normal processing under a controlled correction policy, and making the application route the blocked record to a correction workflow. The choice should reflect who can resolve the missing fact and how much normal work would otherwise stop.
Use the actual deployment overlap window. When different versions of a writer can coexist, test the oldest one that is still allowed to send a write. Then test the new version against both preexisting and staged-constraint data. If a queue consumer can continue to run old code after the web application has deployed, the writer readiness milestone is still open. Record the old instance evidence and decide how the change becomes true for it. A compatibility proof at the interface where the row is written is stronger than a deployment timestamp.
Test valid behavior through each writer rather than only from a SQL console. Use representative user actions, background tasks, and imports. An action intended to assign a reviewer and approve in two consecutive statements may succeed before the constraint while placing those statements in the wrong order. A CHECK intended to protect each stored row has an immediate effect on the first update which creates an invalid row. Change the writer to perform the transition together where the product requires it. If the transaction is split across services, identify what can actually be guaranteed at the database write and choose valid intermediate states.
Record each result as an observable effect. For example, the new admin path should create an approved row that reads back with the reviewer it was given, an attempted approval with a missing reviewer should be rejected by the intended rule, and a note edit on a valid row should still write and display the new note. Include a denied path using real permission behavior so a writer change made in the name of compatibility does not accidentally make approvals available to more people. Keep the test identities synthetic and the required permission role explicit.
Capture the baseline and decide what you will hold
Identify the database, relation, schema, PostgreSQL major version, and name of the intended constraint before the migration. Use a schema-qualified relation in runbooks and checks. The same simple table name can occur in different schemas, particularly when an evaluation team has cloned production structures for testing. A vaguely scoped catalog query can match the right-looking name on the wrong relation. Treat a mismatch in relation or rule text as a stop requiring investigation.
Take a read-only baseline that counts the intended exception predicate and separates open work from low-touch history. Use the same rule the constraint is meant to express. For the example, a useful observation is the count of approved rows with no reviewer, split by source system and time period, plus a few authorized record references for follow-up. If status is allowed to be null, an exception report that uses only equality to approved will omit those rows. That is appropriate only if null status is handled by another policy. Compare the report's actual predicates to the table of expectations before interpreting the denominator.
An initial count gives a starting position. Concurrent writes or corrections can change it between observations. Record the observed window and data source. If the count must support a decision across multiple reports, read them under a consistent snapshot or record which observations came from different times. Avoid assigning each change in the total to the repair effort unless you can account for new writes, concurrent corrections, and other changes during the window. Use row identities and durable change evidence to determine what your own operation corrected.
Agree in advance on the behavior a writer or reader will use if the migration cannot advance. A reasonable hold point is an active writer that cannot create valid rows or a large unresolved exception set with no authoritative repair path. A lock wait that exceeds the approved window is also a useful hold point. During a hold, keep users on behavior that remains supported by the currently observed state. The owner can change the policy, allocate a data steward, or schedule a quieter window if the evidence identifies what is needed. A migration task with a deadline still needs a supported branch for a missed deadline.
Add the rule in a short, bounded transaction
After writer checks pass, add the constraint with NOT VALID. The PostgreSQL documentation says the form skips the initial scan and that after commit the constraint is enforced for new or updated rows. PostgreSQL normally takes an ACCESS EXCLUSIVE lock for ALTER TABLE subcommands unless a different lock mode is specified. Expect the add to need a suitable lock window even when it does no verification scan. Check the documentation for the actual subcommand, release, and relation layout. Give the migration a bounded lock wait appropriate to the environment and keep unrelated work out of the same transaction. PostgreSQL ALTER TABLE
ALTER TABLE review.ai_reviews
ADD CONSTRAINT approved_review_has_reviewer
CHECK (review_status <> 'approved' OR reviewer_id IS NOT NULL)
NOT VALID;
Immediately after the transaction, use a different authorized connection to inspect the constraint's name, definition, validation status, and relation. The expected staged state is the named rule present and unvalidated. A migration tool's success line establishes only its own report. The catalog state establishes that the DDL reached the database you inspected. Use a valid writer transaction beside it to show that normal work remains possible. Use a synthetic invalid transaction to show that enforcement is active. These observations cover different boundaries and are complementary.
SELECT
conname,
convalidated,
pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE conrelid = 'review.ai_reviews'::regclass
AND conname = 'approved_review_has_reviewer';
If the apply call times out or its response is lost, inspect from a new connection before retrying. The command can have acquired a lock and committed before the client lost its reply. If the named constraint is present with the expected rule, use the observed status to resume. If it is absent, also check whether another attempt or an unfinished transaction can still change the table. A name collision with a different definition is a defect in the handoff or a concurrent change that needs reconciliation. Similar names and different predicates should never pass the same release test. PostgreSQL constraint catalog
Test the bounded lock behavior in a disposable environment. Hold a conflicting transaction from another session and run the add with a deliberately small test lock wait. The expected result is a clear failure followed by an inspection confirming the intended schema state. Release the holder and rerun the ordinary migration path under the agreed conditions. During a production timeout, use the observation to determine whether scheduling or an unfinished transaction is responsible. Stopping after the timeout protects the service from repeated attempts that recreate the same lock queue.
The lock mode required by an add can make transaction hygiene more important than the number of constraint expressions. An application may leave an explicit transaction open while waiting for a remote result or a human decision. A schema operation scheduled before those transactions finish can block even when the table is quiet by a simple read or write counts dashboard. Inspect actual connection and transaction behavior in staging. Use the maintenance window to bring the blocker class within a known bound, and make the direction of the observed wait part of the evidence.
Run the staged migration on deliberately imperfect data
Build a disposable relation with one legacy approved row lacking a reviewer, one valid approved row, and one pending row without a reviewer. Label them A, B, and P in the fixture ledger. Give A a reference to an archived human decision that clearly identifies the reviewer and reviewed document revision. Then create a separate fixture A2 in which neither the review system nor the archival decision carries the necessary link. A2 is a test of how the correction workflow behaves when the task cannot be completed from its sources.
First observe A, B, and P with the exception query. Only A should be returned under the documented predicate. Add the unvalidated constraint and confirm the same exception is still present from a new connection. A direct SELECT of the old data should succeed. The migration must neither hide the row from the database nor repair it by inference. Use an auxiliary transaction to try creating another approved row without a reviewer. Assert that the error identifies the expected constraint. Then try the valid and pending cases in separate transactions. PostgreSQL marks a transaction failed after an ordinary SQL error until rollback or a suitable savepoint recovery. The positive controls need an independent opportunity to commit.
| Staging probe after the add commits | Expected database evidence | What a surprising result calls for |
|---|---|---|
| Approve a new record with a null reviewer | The named rule rejects the write | Inspect the deployed predicate, writer input, connection target, and any other error |
| Approve a valid record with an authorized reviewer | The real writer commits and a fresh read shows that reviewer | Check other constraints, stale clients, and authorization before interpreting the new rule |
| Keep a record pending without a reviewer | The new rule permits it | Review state-domain rules and whether the application changed the attempted state |
| Edit an unrelated field on legacy record A | The stored row still violates the rule, so the update is rejected | Confirm the test used an actual row-changing update and a fresh staged baseline |
| Validate while A remains invalid | Validation fails and the named rule remains unvalidated | Inspect the relation, check definition, fixture ID, and transaction outcome |
| Resolve A from the archived decision and validate again | The exception query is empty and the catalog records validation | Check for untracked writers, different relations, or partial repair |
| Investigate A2 without supporting evidence | The case goes to a correction owner without a guessed reviewer assignment | Preserve that unresolved condition in the release decision |
Before repairing A, run the expected failed validation. Save its error and check the validation flag from a fresh connection. Failure is an observation you want in this fixture. It distinguishes a meaningful scan from a harness that chooses the wrong table or starts with no violations. To challenge the harness, deliberately point its precheck at a test relation without the exception. The complete test should object to the identity mismatch or missing adverse fixture. If the test still reports successful staging, fix the observation contract before using its results in a release decision.
Then apply a narrow correction to A, reread its approval attribution through the reader that will depend on it, and validate again. Assert both the absence of the historical exception and that the intended constraint became valid. A row count cannot detect whether the wrong reviewer was attached, and a correct reviewer on A cannot establish completion for every row. Keep the assertion for the exact row, the exception predicate, and the catalog flag. Where A2 is included, keep the expected hold explicit or apply an owner-approved disposition that changes the row to a state consistent with the actual historical record.
Repair historical records with their evidence attached
Use a repair operation that can explain the previous representation and the new one. For each affected record, keep its stable ID, source occurrence, document revision, proposed correction, evidence owner, and expected current state. Store the new reviewer only when direct evidence ties that person to the decision on the same document revision. A reviewer assigned to a later version, someone who queued the item, or a person who edited a comment may be identifiable in nearby records. Their presence does not prove who authorized the original approval.
Keep different correction classes distinct. If an authoritative audit event identifies a reviewer, the repair can restore a known attribution. If policy says a missing approval must be reviewed again, the case can reenter review under an explicit workflow and get new evidence. If a record should have been archived rather than approved, the correction changes state according to the data owner's policy. Those actions have different consequences for users, and they should not be silently implemented by writing a placeholder reviewer to satisfy the predicate.
Guard the update against a changed record. For example, require the observed approval state and document revision to match the evidence used for the proposed repair. In a real system, use whichever row version or other application concurrency control governs simultaneous changes. A zero-row update is a useful signal that someone already changed the case or the scope was wrong. Re-read and ask the correction workflow what the current evidence permits. Blindly proceeding with an outdated repair can turn a missing fact into a false one.
Run the repair in limited batches chosen for the environment. Track successfully applied changes separately from skipped, unresolved, and ambiguous rows. A failed batch can be rolled back while earlier batches remain committed. A resumed operation should begin from actual durable results and its original scope. Confirm lock duration, write cost, and any replication or downstream processing impact before raising the batch size. On a particularly busy table, a small verified pass tells you more about the safe rate than a target deadline from a quiet staging copy.
Make the error surface part of the application work. A note editor reaching a quarantined record should get a practical next action, such as contacting the reviewer attribution owner, when that is the actual recovery route. Logging a constraint failure under a generic inference error gives the product operator the wrong cause. In a successful repair, observe the previously blocked supported action become usable without relaxing the new rule on a separate deliberately invalid input.
An exception census should also include records your inventory cannot read because they are outside its allowed dataset. Knowledge that a report covers one partition, region, or tenant is essential when someone asks whether the entire history is clean. The database validation scans the relation targeted by the command according to its actual schema and version semantics. The business decision about every served record also depends on whether the application uses other relations, archived tables, views, or restored copies. Put those boundaries into the release record.
Work through a repair ledger before choosing a validation date
In an illustrative migration review, a scoped exception query returns eighty approved rows with missing attribution. The records come from a legacy import and a newer approval path. The source register can identify the original approval and exact document revision for sixty of them. Archive links for another twelve point to documents that were reviewed on a different revision. The remaining eight have no recoverable decision reference. The visible defect is the same on all eighty rows, but the eighty rows cannot go through the same repair.
Start by preparing sixty attributable proposed corrections. When applying them, a version guard reports that three of those sixty have changed since the inventory. The other fifty-seven repairs commit. The expected remaining inventory is twenty-three if nobody else changed the exception set. Use this arithmetic as a sense check. Read the current set and reconcile the changed identities rather than relying on subtraction. A colleague could have corrected several old records while this batch was running. The correct statement about this batch is that fifty-seven intended changes were confirmed, and the final count needs its own observation.
Reread the three version conflicts. In this example, two now have verified attribution and one still needs investigation after an unrelated edit. Assume the final exception query returns twenty-one unresolved cases, including that conflict, the twelve revision mismatches, and the eight without a reference. The arithmetic now agrees with the recorded groups. The operator still needs to inspect key coverage and evidence owners. Twenty-one unresolved gives no basis to select an arbitrary reviewer for any of them.
| Cohort after the fresh read | Count in this example | Practical next action |
|---|---|---|
| Successful direct repair with readback | 57 | Retain the evidence link and applied row version |
| Independently repaired before recheck | 2 | Verify the observed reviewer and record the actual source |
| Conflicting change with unresolved attribution | 1 | Reopen the affected decision against the latest record |
| Archived review refers to a different document revision | 12 | Ask the review owner whether to reopen or restore a supported record |
| No recoverable decision reference | 8 | Use the approved correction policy or keep the case unresolved |
The constraint can still protect current inserts and updates while the twenty-one cases are handled. If the business owner authorizes a re-review for a subset, those records can acquire a new decision with its own provenance. The report should distinguish that outcome from restoring original attribution. If other records need to remain approved for a reason the constraint cannot represent, resolve the policy conflict in the data model. Schedule a validation only when you know what each remaining case should mean under the final rule.
Use this ledger to negotiate review time. The approval owner can work on the twelve revision mismatches, the data steward can reconcile the one conflicting change, and the record custodian can investigate the eight missing references. An operator who receives a batch marked merely seventy-four percent complete cannot derive those assignments. Counts are useful when tied to actual dispositions and owners. That lets the project advance legitimate work while retaining the reason the validation milestone remains open.
Validate only after the repair evidence supports it
After the add is committed, PostgreSQL can validate the existing rows because concurrent new and updated rows are already subject to the rule. The PostgreSQL 18 ALTER TABLE reference documents a SHARE UPDATE EXCLUSIVE lock for the validation step. The lighter lock does not make the scan cost free. Check compatibility with other planned maintenance, available storage and database capacity, and the time the operation may run on the actual relation. For foreign key validation there are also requirements on the referenced relation. This guide's fixture covers a CHECK on one table. PostgreSQL ALTER TABLE notes on validation
SELECT count(*) AS unresolved_approved_rows
FROM review.ai_reviews
WHERE review_status = 'approved'
AND reviewer_id IS NULL;
ALTER TABLE review.ai_reviews
VALIDATE CONSTRAINT approved_review_has_reviewer;
Treat the count before validation as preparation. The validated state should be read separately after commit. An observed zero gives a reason to expect the validation to pass under the stated predicate and scope. A failed validation with an observed zero can indicate a different predicate or relation, a different time window, or an unsuccessful transaction. Inspect each in turn. Avoid repeatedly launching the same scan when the expected data state and the actual constraint definition have never been compared.
If the validation fails because an old exception remains, the already committed add still provides its enforcement for new and updated rows. Read the catalog and run the scoped exception report to check that assumption before resuming the repair. Keep the failed validation in the audit trail together with which legacy condition it exposed. If an unexpected infrastructure interruption leaves the outcome unclear, read the catalog independently before trying again. The previous command may have achieved a durable outcome the migration runner did not receive.
For a partitioned or inherited table, verify the shape you actually use. The specific DDL syntax, inherited definitions, and catalog rows can differ from a single local table. Freeze parent and child relation identities and ask which relation the application truly writes and serves. Run the adverse fixture through the same routing path. When adopting a different constraint kind or PostgreSQL major version, check its documented operations. Unique constraints and primary keys have their own rollout techniques, and an adaptation should show the guarantees of that actual technique. PostgreSQL ALTER TABLE and version-specific forms
Release readers only after a fresh end-to-end check
Check the reader as a different participant. It may assume every approved row has a reviewer and then join to a display name, generate an approval report, or transfer the record to another system. The reader may access a replica, cache, or export refreshed more slowly than the schema migration. Inspect the real read path for an approved row corrected during the migration. Check that its exposed value matches the approved source and that the expected visibility rules still apply. A successful catalog query on the primary leaves these other observations open.
Watch for a graceful legacy mode that disappears too early. Before validation the reader can display pending attribution as an exception with an owner, hide an incomplete field according to the product policy, or decline to generate a report that would misrepresent the data. After validation, release the stronger assumption only for the scope that was actually proved. A mixed report covering both the repaired table and older exports may need to retain its exception branch indefinitely. The reader's compatibility policy should follow the evidence available for each source.
Capture a minimal release worksheet. Record installed version, relation identity, staged rule text, writer versions and paths tested, exception scope and unresolved cases, add and validation observations, and expected reader state. Pair each item with the actor who can confirm it. During an incident this separates the control owner who can verify the database from the product owner who can decide a case's corrected disposition. The final check should work for someone who never watched the migration and has only the approved evidence and their ordinary operational access.
Use a concrete recovery decision when a reader or writer regresses. If the issue is a missing historical record, a data correction may be appropriate. If a valid writer cannot obey the published policy, fix the writer or arrange a controlled pause for that operation. Removing a deployed constraint changes the protection new writes receive and should be an explicit, reviewed recovery operation with an observed result. Reader rollback has its own boundary. It may be possible to reinstate exception handling without changing the enforced row rule. Assess those effects independently instead of treating schema rollback and application rollback as the same switch.
Compare the two rollout options on one maintenance scenario
Suppose a document review service has one large history relation, several old approvals with missing attribution, and a small group of support staff who edit current records during the day. Treat this setup as illustrative. Adding and validating in one operation keeps enforcement and validation close together if the statement succeeds. It cannot succeed with the known invalid history still present, and scanning as part of the add can extend the blocking work. Staging brings enforcement forward after writer compatibility testing and allows historical repair to have its own pace. It also means some old rows remain visible with exceptions until validation completes.
Choose the immediate route when the exact relation is already clean, the lock and scan fit a measured safe window, and there is a straightforward verification path. Use staged CHECK when protecting new writes sooner matters and the historical backlog can be repaired under a controlled exception policy. Delay either route when working writers would be blocked by the intended rule or when the product cannot define what to do with unresolved history. The primary distinction is the proof each phase provides. Stage only if the intermediate state is meaningful to the business and operable by the people who maintain it.
Measure a comparable run in staging for both strategies rather than estimating a universal time saving. Use the same representative table and workload. Record lock acquisition latency, observed writer interruptions, scan duration, and which rule checked which rows. Include a case already known to violate the rule and document its effect separately. A quiet run on a small table can prove SQL correctness without demonstrating an acceptable lock window. State that boundary in the decision.
Give the reader migration its own approval. After the catalog confirms validation, read the application through both a previously exceptional record and a new record. Retire the old exception behavior only after the intended revised read path is observed for both.
FAQ
Does NOT VALID mean a PostgreSQL CHECK is disabled?
No. For the staged CHECK described here, the add skips the scan of existing rows. Once the add commits, PostgreSQL checks new and updated rows. Confirm the distinction by observing the intentional old exception and a rejected new insert in the same staged fixture. If either observation is missing, the catalog flag alone does not explain the cause. PostgreSQL ALTER TABLE
Can I update an unrelated field on an invalid old row?
The update forms a new row version and can be rejected when it still violates the rule. Verify through the real support or background writer because application statements, exception handling, and follow-up updates can differ. If an operator cannot supply the missing fact, route the case to the authorized correction process. Treat preserving access to ordinary valid writes as an acceptance test for the migration.
Why can the exception count be zero while the rule remains unvalidated?
The report and the catalog describe different things. The report inspects visible rows at one point under its predicate. The catalog flag changes after the actual validation operation succeeds. Confirm the exact relation and rule, run the documented validation, then read the actual catalog result. Preserve the precheck and final flag as complementary evidence. PostgreSQL constraint catalog
What if the approval rule seems to require checking a second table?
Decide which guarantee you need. Requirement that a reviewer reference exists may fit a foreign key. Requirement that the reviewer had authority for the specific decision may need a business operation that binds evidence and current state. The CHECK here proves reviewer presence on one row. Consult the installed version's documented constraint types and test the real decision boundary before promising something broader. PostgreSQL constraints
When can a downstream report trust reviewer attribution?
First determine what “trust” means for the report. Validation confirms the defined stored presence rule on the covered relation. Attributable historical identity requires delivery of the correct evidence-backed value, and access rights depend on the actual reader. Verify each of those facts through its authoritative source. Keep cases from other relations or immutable exports under the policies that apply to those sources.
What should I save when validation times out?
Save the relation, constraint name, expected definition, attempted operation, and time window. Read the actual flag and related schema from a fresh connection before scheduling another action. If validation remains unconfirmed, preserve the staged writer behavior and the historical hold while you investigate. This keeps an uncertain runtime outcome from being mistaken for permission to replace the rule or to give readers a stronger guarantee.
sinc-LLM