CHECK Constraint
Last updated: 2026-11-04
CHECK Constraint
A CHECK constraint requires the values in a column or group of columns to satisfy a given condition, and is the usual way to push business rules down into the database. It is evaluated per row and cannot query across rows or other tables, so it suits row-level rules such as 'amount must be positive' but not aggregate rules such as 'the total must not exceed the budget'.
| Kind | constraint |
|---|---|
| Example Language | SQL |
📝 Syntax
Column level: `column_name type CHECK (expression)`
Table level: `CONSTRAINT constraint_name CHECK (expression)`
Multi-column: `CHECK (col_a > 0 AND col_b < col_a)`
⚙️ Parameters
| expression | A boolean expression evaluated per row; the row is rejected when it yields false or NULL. It must be immutable and cannot reference other tables. |
|---|
Returns:A CHECK constraint has no return value. On violation PostgreSQL raises `new row for relation "..." violates check constraint "..."`.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
SELECT 'insert price = 19.99' AS step, 'OK' AS result
UNION ALL SELECT 'insert price = -1.00', (SELECT pg_try('INSERT INTO products VALUES (3,''Broken'',-1.00)'))
UNION ALL SELECT 'rows stored', (SELECT count(*)::TEXT FROM products)
step | result
----------------------+-------------------------------------------------------------------------------------
insert price = 19.99 | OK
insert price = -1.00 | new row for relation "products" violates check constraint "products_price_positive"
rows stored | 2
(3 rows)
📌 Key Points
- A NULL result also fails the check, since CHECK requires the expression to evaluate to true.
- Once a column-level CHECK references another column, PostgreSQL promotes it to a table constraint and names it `
_check` instead of `
_
_check`. - The expression must be immutable, so volatile functions such as now() and random() are not allowed.
- To add a CHECK to a populated table, use `ADD CONSTRAINT ... NOT VALID` to cover new rows first and validate later.
💡 Related Cases
More case studies coming soon.📚 Related Reference
❓ FAQ
QHow does CHECK differ from NOT NULL?ANOT NULL expresses only the 'no NULLs' rule, while CHECK expresses any boolean condition, including compound ones such as 'not null and greater than zero'. They can be combined; NOT NULL is semantically more precise and is better understood by the planner.QCan a CHECK constraint reference another table?ANo. A CHECK expression may not contain subqueries or reference other tables, unlike in some other databases. For cross-table validation, use a foreign key, a trigger, or express the rule as a view with a JOIN.🙏 帮我们做得更好
我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……
如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏