CHECK constraints
CHECK constraints on columns and tables, when they are tested, the errors they give and the known gaps.
A CHECK constraint is a condition every row must satisfy (D73).
Syntax#
-- column constraint
col_name data_type CHECK (expr) [[NOT] ENFORCED]
-- table constraint
[CONSTRAINT [symbol]] CHECK (expr) [[NOT] ENFORCED]
ALTER TABLE tbl_name ADD [CONSTRAINT [symbol]] CHECK (expr) [[NOT] ENFORCED]
ALTER TABLE tbl_name DROP CHECK symbol
ALTER TABLE tbl_name DROP CONSTRAINT symbolArguments#
| Name | Meaning | Default |
|---|---|---|
expr | A condition. A row passes when it is true or NULL. | none |
symbol | Constraint name. Unnamed ones are table_chk_n (n after the highest in use). | generated |
NOT ENFORCED | Stored and shown, not tested. | ENFORCED |
Remarks#
- The constraint is kept in the table's definition: its name, the condition as written, whether it is enforced.
- Every enforced condition is evaluated against the row about to be written by
INSERT,REPLACE,ON DUPLICATE KEY UPDATE,UPDATEandINSERT ... SELECT. A condition that is false (not NULL) is error 3819Row rejected by check constraint 'name'.. The statement is undone as always. - A multi-row insert into a table with a check is written row by row (not sent to Raft DB as one batch).
- Adding a check to a table checks the rows already in it.
- Errors as MySQL: 3822 duplicate name, 3813 a column constraint naming another column, 1054 unknown column, 3821
DROP CHECKof a name that is not there. SHOW CREATE TABLElists the constraints sorted by name with the condition printed as MySQL prints it (every operation in parentheses,<>for a negated=,_utf8mb4'x'for strings).CREATE TABLE ... LIKEcopies checks under new names (new_chk_n).- The output is identical to MySQL 9.7.
Not supported yet#
INSERT IGNOREstops with the error where MySQL skips the row with a warning.ALTER TABLE ... ALTER CHECK name [NOT] ENFORCED.- A column that a check names can be dropped or renamed without the check being looked at.
information_schema.CHECK_CONSTRAINTSandTABLE_CONSTRAINTSrows for checks.- Cascading foreign-key updates do not run the child table's checks.
- The introducer of a string literal in
SHOW CREATE TABLEis always_utf8mb4.
Examples#
Example:
CREATE TABLE t (id INT PRIMARY KEY, qty INT CHECK (qty >= 0), price DECIMAL(8,2),
name VARCHAR(10), CONSTRAINT price_pos CHECK (price > 0),
CONSTRAINT name_ok CHECK (CHAR_LENGTH(name) >= 2));
INSERT INTO t VALUES (1, 5, 1.50, 'ab'); -- ok
INSERT INTO t VALUES (2, -1, 1.50, 'ab'); -- error 3819
INSERT INTO t VALUES (7, NULL, NULL, NULL); -- ok: NULL passes
ALTER TABLE t DROP CHECK price_pos;
ALTER TABLE t ADD CONSTRAINT price_pos CHECK (price > 0);
CREATE TABLE t2 (a INT, b INT, CONSTRAINT ab CHECK (a < b) NOT ENFORCED);