Combining Column Defaults and Checks

A default supplies a value under its rules. A check enforces a condition when candidate rows are stored. Choose them to agree at the insertion boundary.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace an interval default
  2. Test multiple insertion paths
  3. Evaluate the effective value before validating it
  4. Check the continued validity of defaults during migration

Trace an interval default

A quantity default of one should pass a constraint requiring 1 through 10. Changing the default to zero would break inserts omitting quantity. See default column values.

Test multiple insertion paths

Insert with omission, explicit boundary values, and an explicit invalid value. Keep null behavior explicit if it is allowed. Check constraints describe how that result is evaluated.[1][2]

Evaluate the effective value before validating it

A priority column can default to two and accept integers from one through four. Omitting it stores two. An explicit zero violates the permitted range. If the column also requires presence, explicit null fails the presence rule. See defaults for omitted values.

Omitted → effective 2 → accepted
Explicit 4 → accepted
Explicit 0 → rejected
Explicit null → rejected when NOT NULL applies

Check the continued validity of defaults during migration

Tightening a range can make an earlier default invalid. Update both according to the desired contract and test omitted input. Check stored values because changing the default alone does not repair prior rows.

References

  1. PostgreSQL Global Development Group, Data Definition ↩
  2. PostgreSQL Global Development Group, SQL Language Tutorial ↩