Sub topic 10
Validating Document Shape with `CHECK` Constraints
Assume you know basic CREATE TABLE, INSERT, and SELECT statements, and that you understand JSON objects, arrays, strings, and numbers. This chapter uses PostgreSQL's jsonb type.
A JSON column gives each row a flexible document shape. That flexibility is useful, but it can also allow invalid documents into the database. A CHECK constraint is a rule that PostgreSQL tests before accepting or changing a row. Use it to require a document type, required keys, and specific JSON value types.
Require an object and required keys
Start with a table whose JSON document must represent an order:
CREATE TABLE orders_validated (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
details jsonb NOT NULL,
CONSTRAINT details_is_object
CHECK ((jsonb_typeof(details) = 'object') IS TRUE),
CONSTRAINT details_has_status
CHECK ((details ? 'status') IS TRUE)
);jsonb_typeof returns the JSON type of a value, such as object, array, string, or number. The ? operator tests whether a top-level key exists.
The IS TRUE wrapper is important. A CHECK constraint passes when its expression is either true or null. If a missing JSON path produces null, a constraint without IS TRUE might allow a row that you meant to reject.
For example, this insert satisfies both constraints:
INSERT INTO orders_validated (customer, details)
VALUES (
'Ada',
'{
"status": "paid",
"total": 42.50,
"items": [{"sku": "A1", "qty": 2}]
}'
);This insert fails because the document has no status key:
INSERT INTO orders_validated (customer, details)
VALUES ('Grace', '{"total": 10.00}');Validate the type of a key
Checking that a key exists does not guarantee that it contains the right kind of value. The status value could be a number, array, or JSON null. Add a type check:
ALTER TABLE orders_validated
ADD CONSTRAINT status_is_string
CHECK (
(details ? 'status'
AND jsonb_typeof(details -> 'status') = 'string') IS TRUE
),
ADD CONSTRAINT total_is_number
CHECK (
(details ? 'total'
AND jsonb_typeof(details -> 'total') = 'number') IS TRUE
),
ADD CONSTRAINT items_is_array
CHECK (
(details ? 'items'
AND jsonb_typeof(details -> 'items') = 'array') IS TRUE
);The -> operator returns a JSON value, so it works with jsonb_typeof. If status is missing, the explicit details ? 'status' test makes the whole condition false instead of null.
A constraint can enforce the outer shape, but complex rules may need more work. For example, checking that every item has a string sku and a positive integer qty usually requires a trigger, application validation, or a query that expands the array and inspects each element.
| Rule | Example expression | What it checks |
|---|---|---|
| Document type | `jsonb_typeof(details) = 'object'` | The root value is an object |
| Required key | `details ? 'status'` | A top-level key exists |
| Value type | `jsonb_typeof(details -> 'total') = 'number'` | A key contains a JSON number |
| SQL column presence | `details IS NOT NULL` | The column itself is not SQL `NULL` |
Choose constraints deliberately
Constraints should protect assumptions that the database can check cheaply and consistently. They are especially useful for fields that every query expects, such as a document version, status, or tenant identifier.
Do not use a JSON column merely to avoid defining rules. If a value is required for joins, uniqueness, foreign keys, sorting, or frequent filtering, a normal relational column may be clearer. You can also keep important fields in columns and store less predictable attributes in jsonb.
Exercise
Why should a constraint that checks jsonb_typeof(details -> 'status') = 'string' also check that the status key exists, or wrap the expression with IS TRUE?
Show answer
A missing key produces SQL NULL. PostgreSQL treats a NULL CHECK result as passing, so the constraint could allow a document without status. An explicit existence test or IS TRUE makes the missing-key case fail.