Sub topic 10
Validating document shape with CHECK constraints
This chapter assumes you know basic SQL, can read JSON syntax, and have worked through the earlier chapters on jsonb operators, containment, and jsonb_typeof. You need PostgreSQL 12 or later. The orders table from earlier chapters is the running example.
Why a JSON column needs constraints
A jsonb column accepts any valid JSON. The type checks syntax and nothing else. These values all pass a plain jsonb NOT NULL column:
{"status": "paid"}[1, 2, 3]"hello"null(the JSON null, which is not the same as SQLNULL){}
Your queries usually assume a specific shape, for example "an object with a status key that holds a string". Without a constraint, one bad insert can make details ->> 'status' return NULL for a row. It can also make jsonb_array_elements raise an error halfway through a report. A CHECK constraint moves that failure to write time, where the application gets an immediate error.
A CHECK constraint is a boolean expression attached to a table. PostgreSQL evaluates it for every inserted or updated row. It rejects the row if the expression returns false.
Setting up
The following statements recreate the table from earlier chapters. Run them in a scratch database.
DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
details jsonb NOT NULL
);
INSERT INTO orders (customer, details) VALUES
('Ada', '{"status": "paid", "total": 42.50, "items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}], "shipping": {"city": "Oslo"}}'),
('Grace', '{"status": "pending", "total": 10.00, "items": [{"sku": "A1", "qty": 1}], "shipping": {"city": "Bergen"}}');Checking the top-level type
The first constraint to add is a check that the document is an object. jsonb_typeof returns one of object, array, string, number, boolean, or null.
ALTER TABLE orders
ADD CONSTRAINT details_is_object CHECK (jsonb_typeof(details) = 'object');Now test it:
INSERT INTO orders (customer, details) VALUES ('Linus', '[1, 2, 3]');PostgreSQL rejects the insert with an error like this:
ERROR: new row for relation "orders" violates check constraint "details_is_object"Because the column is NOT NULL, SQL NULL is already blocked. The JSON null literal is a different value. It has type null in jsonb_typeof, so this constraint rejects it too.
Requiring keys
The ? operator tests whether a top-level key exists. Use it to require keys.
ALTER TABLE orders
ADD CONSTRAINT details_has_status CHECK (details ? 'status');To require several keys at once, use ?&, which takes a text array and is true only if all of the keys are present:
ALTER TABLE orders
ADD CONSTRAINT details_has_core_keys
CHECK (details ?& ARRAY['status', 'total', 'items']);Existence is only half of the check. A document such as {"status": null} has the key status, so ? returns true. If you also need a real value, check the type of the value.
Checking the types of values
Use jsonb_typeof on extracted values. Use -> rather than ->> here, because ->> converts to text and loses the JSON type.
ALTER TABLE orders
ADD CONSTRAINT details_field_types CHECK (
jsonb_typeof(details -> 'status') = 'string'
AND jsonb_typeof(details -> 'total') = 'number'
AND jsonb_typeof(details -> 'items') = 'array'
);If a key is missing, details -> 'status' returns SQL NULL. Then jsonb_typeof(NULL) is NULL, and the comparison is NULL. This leads to the most important rule in this chapter.
How CHECK treats NULL
A CHECK constraint rejects a row only when the expression is false. If the result is NULL, the row passes. Compare these two constraints:
-- Passes when status is missing, because the expression is NULL
CHECK (jsonb_typeof(details -> 'status') = 'string')
-- Rejects when status is missing, because the expression is false
CHECK (coalesce(jsonb_typeof(details -> 'status'), '') = 'string')In details_field_types above, the missing-key case would therefore slip through if you relied on the type test alone. That is why the earlier details ? 'status' and ?& constraints matter. Pair a presence check with a type check, or use coalesce as shown, so that a missing key cannot produce NULL.
Checking value ranges and formats
Once a value has the right type, you can constrain its content. Casting is safe only after the type check passes, and SQL does not promise that AND evaluates left to right. A cast such as (details ->> 'total')::numeric raises an error on non-numeric text. A CASE expression guarantees the order of evaluation:
ALTER TABLE orders
ADD CONSTRAINT details_total_non_negative CHECK (
CASE
WHEN jsonb_typeof(details -> 'total') = 'number'
THEN (details ->> 'total')::numeric >= 0
ELSE false
END
);The ELSE false branch rejects documents where total is missing or is not a number. This constraint therefore also enforces presence.
You can restrict a field to a fixed set of values with IN:
ALTER TABLE orders
ADD CONSTRAINT details_status_allowed CHECK (
details ->> 'status' IN ('pending', 'paid', 'shipped', 'cancelled')
);A missing status gives NULL here, which passes. The details_has_status constraint already rejects that case.
Checking array contents
Constraints cannot contain a subquery. In PostgreSQL, a CHECK expression cannot use SELECT, so you cannot write NOT EXISTS (SELECT ... FROM jsonb_array_elements(...)) directly. You have two options.
The first is the SQL/JSON path predicate operator @@, which returns a boolean from a path predicate. It works directly in a CHECK. This constraint rejects any order that contains an item with a quantity of zero or less:
ALTER TABLE orders
ADD CONSTRAINT details_items_qty_positive
CHECK (NOT jsonb_path_exists(details, '$.items[*] ? (@.qty <= 0)'));jsonb_path_exists returns true when the path finds at least one match. Negating it means "no item has a non-positive quantity". The path language needs PostgreSQL 12 or later.
The second option is a helper function. Wrap more complex logic in an IMMUTABLE SQL function and call it from the constraint:
CREATE FUNCTION items_are_valid(items jsonb) RETURNS boolean
LANGUAGE sql IMMUTABLE AS $$
SELECT coalesce(bool_and(
jsonb_typeof(i -> 'sku') = 'string'
AND jsonb_typeof(i -> 'qty') = 'number'
), true)
FROM jsonb_array_elements(items) AS i
$$;
ALTER TABLE orders
ADD CONSTRAINT details_items_shape
CHECK (jsonb_typeof(details -> 'items') = 'array'
AND items_are_valid(details -> 'items'));The function uses coalesce(..., true) so that an empty array counts as valid, because bool_and over zero rows returns NULL. jsonb_array_elements raises an error if its argument is not an array, so the array check must run first. The function is not truly guaranteed to run after it. If you need a strict order, put the type test inside the function too.
Testing constraints
Test each constraint with one valid and one invalid row. Valid insert:
INSERT INTO orders (customer, details) VALUES
('Edsger', '{"status": "paid", "total": 5, "items": [{"sku": "C3", "qty": 1}]}');Invalid inserts, each of which should fail:
INSERT INTO orders (customer, details) VALUES
('Bad1', '{"status": "paid", "total": "5", "items": []}');
INSERT INTO orders (customer, details) VALUES
('Bad2', '{"status": "refunded", "total": 5, "items": []}');
INSERT INTO orders (customer, details) VALUES
('Bad3', '{"status": "paid", "total": 5, "items": [{"sku": "C3", "qty": 0}]}');Bad1 fails because total is a string. Bad2 fails because refunded is not an allowed status. Bad3 fails because the quantity is zero. Constraints also apply to updates, so jsonb_set can no longer write an invalid value:
UPDATE orders
SET details = jsonb_set(details, '{status}', '"lost"')
WHERE id = 1;This update fails on details_status_allowed.
Adding constraints to a table that already has data
ALTER TABLE ... ADD CONSTRAINT ... CHECK scans every row and fails if any row violates the rule. It also takes a lock that blocks writes while it scans. On a large table, use the two-step form:
ALTER TABLE orders
ADD CONSTRAINT details_has_tracking_field
CHECK (details ? 'status') NOT VALID;
-- Fix existing bad rows, then:
ALTER TABLE orders VALIDATE CONSTRAINT details_has_tracking_field;NOT VALID makes PostgreSQL enforce the rule for new and updated rows right away, without scanning old rows. VALIDATE CONSTRAINT then scans the existing rows with a weaker lock that allows normal reads and writes.
To find rows that would violate a rule before you add it, run the negated expression as a query:
SELECT id
FROM orders
WHERE NOT (details ? 'status') OR (details ? 'status') IS NULL;What CHECK constraints cannot do
- They cannot reference other tables or use subqueries. Use a foreign key on a real column for that.
- They check one row at a time, so they cannot enforce uniqueness of values across rows. Use a unique index, for example on an expression such as
((details ->> 'external_id')). - They are not a full schema language. For deeply nested documents, the expressions become long. Consider a helper function, validation in the application, or an extension that implements JSON Schema.
- They cost CPU on every write. A complex function on a large document slows inserts and updates.
Design guidance
A short list of habits keeps constraints useful:
- Give every constraint an explicit name, as shown above. The error message then tells you which rule failed.
- Require the top-level type first, then required keys, then value types, then value ranges.
- Use
CASEor helper functions when a cast could raise an error. - Keep rules for stable, important fields. If a field is critical enough to constrain heavily, consider moving it to a real column, which the next chapter discusses.
Summary of the operators and functions used
| Tool | Purpose | Returns NULL on missing key? |
|---|---|---|
| `jsonb_typeof(x)` | Type of a JSON value | Yes, if `x` is SQL NULL |
| `details ? 'k'` | Key exists at top level | No, returns false |
| `details ?& ARRAY[...]` | All listed keys exist | No, returns false |
| `jsonb_path_exists(d, path)` | Path finds a match | No, returns false |
| `CASE WHEN ... ELSE false END` | Controls order and the NULL result | Not unless you let it |
Exercise
You add CHECK (jsonb_typeof(details -> 'total') = 'number') to orders. A client inserts {"status": "paid", "items": []}, which has no total key. Does the insert succeed, and why? How do you change the constraint so the insert fails?
Show answer
The insert succeeds. details -> 'total' returns SQL NULL for a missing key, jsonb_typeof(NULL) is NULL, and the comparison is NULL. A CHECK constraint rejects a row only when the expression is false, so NULL passes. To fix it, add a presence test such as AND details ? 'total', or wrap the type in coalesce(jsonb_typeof(details -> 'total'), '') = 'number'.
Exercise
Write a CHECK constraint named details_city_string that requires details -> 'shipping' -> 'city' to be a JSON string and rejects documents that lack it.
Show answer
ALTER TABLE orders ADD CONSTRAINT detailscitystring CHECK (coalesce(jsonbtypeof(details -> 'shipping' -> 'city'), '') = 'string'); The coalesce turns the NULL from a missing path into an empty string, so the comparison is false and the row is rejected. Using `jsonbpath_exists(details, '$.shipping.city ? (@.type() == "string")')` also works.
Exercise
You need to add a new CHECK constraint to a table with 200 million rows that is written to constantly. Which two statements do you run, and why is this safer than a plain ADD CONSTRAINT?
Show answer
Run ALTER TABLE ... ADD CONSTRAINT name CHECK (...) NOT VALID; and then, after fixing any violating rows, ALTER TABLE ... VALIDATE CONSTRAINT name;. The first statement enforces the rule on new writes without scanning old rows. The second scans existing rows with a lock that still allows normal reads and writes, while a plain ADD CONSTRAINT scans everything under a lock that blocks writes.