Checking an Explicit Row Condition

A check constraint can enforce a Boolean condition over a row's values according to the database's constraint evaluation rules.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a measured interval
  2. Consider unknown values
  3. Test valid, reversed and unknown intervals
  4. Keep the checked condition tied to the stored row

Trace a measured interval

An interval row can require end at least start. A row storing 8 then 6 violates it. Range representation defines what the values mean before the check.

Consider unknown values

In PostgreSQL a check is satisfied by true or by a null result. If both endpoints are required, use an appropriate presence constraint as well. SQL three-valued logic explains why the condition alone may permit missing inputs.[1][2]

Test valid, reversed and unknown intervals

A room booking can require ends_at > starts_at. Start at twelve and end at fourteen satisfies the check. Equal times and a reversed interval fail. In PostgreSQL a check succeeds for true or unknown, so required endpoints also need a presence rule. See intervals as pairs.

starts=12, ends=14 → true
starts=12, ends=12 → false
starts=14, ends=12 → false
starts=null, ends=12 → unknown

Keep the checked condition tied to the stored row

If preventing overlapping bookings needs other rows, use a suitable cross-row enforcement mechanism. Test the constraint with inputs the type system permits so the exact failure is visible.

References

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