Sub topic 7
Validating values with CHECK
This chapter assumes you can write basic CREATE TABLE statements, know what NOT NULL, PRIMARY KEY and UNIQUE do, and have an Oracle Database 12c or later schema to run the examples in. You will learn how a CHECK constraint works, which expressions it accepts and rejects, how it treats NULL, and how to name, add, and inspect it.
What a CHECK constraint does
A CHECK constraint is a rule attached to a table. It holds a condition that every row must satisfy. Oracle evaluates the condition on each INSERT and on each UPDATE that touches a column the condition uses. If the condition is false, Oracle rejects the statement with ORA-02290: check constraint (schema.name) violated, and no row from that statement is changed.
Use CHECK for rules that depend only on the row being written, such as:
- A numeric range:
salary >= 0. - A short list of allowed values:
status IN ('ACTIVE', 'INACTIVE'). - A relationship between two columns of the same row:
end_date >= start_date.
The rule lives in the database, so every application, script, and manual UPDATE is held to it.
Syntax: inline and out of line
You can write a CHECK constraint in two places, as with other constraints.
- Inline (column level), directly after the column definition. The condition should refer only to that column.
- Out of line (table level), as a separate clause. The condition can refer to any column of the table.
Both forms accept an optional CONSTRAINT name prefix. Always provide one. Without a name, Oracle generates something like SYS_C0012345, which tells you nothing when an error appears.
CREATE TABLE products (
product_id NUMBER GENERATED ALWAYS AS IDENTITY,
sku VARCHAR2(20) NOT NULL,
list_price NUMBER(10,2)
CONSTRAINT products_price_ck CHECK (list_price >= 0),
sale_price NUMBER(10,2),
status VARCHAR2(10) DEFAULT 'ACTIVE' NOT NULL,
starts_on DATE,
ends_on DATE,
CONSTRAINT products_pk PRIMARY KEY (product_id),
CONSTRAINT products_sku_uk UNIQUE (sku),
CONSTRAINT products_status_ck CHECK (status IN ('ACTIVE', 'INACTIVE')),
CONSTRAINT products_sale_ck CHECK (sale_price IS NULL OR sale_price <= list_price),
CONSTRAINT products_dates_ck CHECK (ends_on IS NULL OR ends_on >= starts_on)
);products_price_ck is inline. The other three CHECK constraints are out of line. The last two compare two columns, so they must be out of line.
Try the constraints:
INSERT INTO products (sku, list_price) VALUES ('A-100', 25.00);
-- Fails with ORA-02290: products_price_ck violated.
INSERT INTO products (sku, list_price) VALUES ('A-101', -5);
-- Fails with ORA-02290: products_status_ck violated.
INSERT INTO products (sku, list_price, status) VALUES ('A-102', 10, 'RETIRED');
-- Fails with ORA-02290: products_sale_ck violated.
INSERT INTO products (sku, list_price, sale_price) VALUES ('A-103', 10, 12);Because the constraint has a name, the error message says which rule failed. You can see products_sale_ck in the message and know where to look.
How CHECK treats NULL
This is the most common source of confusion. Oracle uses three-valued logic: a condition can be true, false, or unknown. A CHECK constraint rejects a row only when the condition is false. When the condition evaluates to unknown, which happens when it compares a NULL, the row passes.
| Value of `list_price` | `list_price >= 0` evaluates to | Row accepted? |
|---|---|---|
| 25 | TRUE | Yes |
| -5 | FALSE | No |
| NULL | UNKNOWN | Yes |
So CHECK (list_price >= 0) does not stop someone from storing a NULL price. If a value must be present, add NOT NULL as well. The two constraints do different jobs. NOT NULL requires a value, and CHECK validates a value that exists.
The same reasoning explains why the two-column rules above include IS NULL OR. Take CHECK (sale_price <= list_price) on its own. A row with no sale price makes the condition unknown, so it passes anyway. Writing sale_price IS NULL OR ... makes the intent explicit and survives a later rewrite of the condition.
The diagram shows how Oracle decides.
What a CHECK condition may contain
The condition is a Boolean expression, similar to a WHERE clause. It can use:
- Comparison operators:
=,<>,<,>=,BETWEEN,IN,LIKE. - Logical operators:
AND,OR,NOT. IS NULLandIS NOT NULL.- Deterministic SQL functions, such as
UPPER,LENGTH,REGEXP_LIKE, orTRUNC. - Only columns of the same table and row.
It cannot contain:
- Subqueries. You cannot write
CHECK (department_id IN (SELECT department_id FROM departments)). Use a foreign key for that. - References to columns of other rows or other tables.
- Non-deterministic functions and pseudocolumns:
SYSDATE,SYSTIMESTAMP,CURRENT_DATE,USER,SYS_CONTEXT,UID,ROWNUM,CURRVALandNEXTVAL.
The restriction on SYSDATE has a good reason. A constraint is a fact about stored data. If it depended on the current time, a row that was valid yesterday could become invalid today, with no statement touching it. Oracle also needs to be able to re-validate the table at any moment, for example when you enable a constraint.
-- Fails with ORA-02436: date or system variable wrongly specified in CHECK constraint.
ALTER TABLE products ADD CONSTRAINT products_future_ck
CHECK (starts_on >= SYSDATE);If you need a rule that depends on the current time, enforce it in a trigger or in the application. Alternatively, set a column default such as DEFAULT SYSDATE, which is evaluated once at insert time and is allowed.
An example using a pattern function:
ALTER TABLE products ADD CONSTRAINT products_sku_fmt_ck
CHECK (REGEXP_LIKE(sku, '^[A-Z]-[0-9]{3}$'));This works because REGEXP_LIKE is deterministic. It also requires that every existing row already match. If one does not, Oracle refuses to add the constraint (ORA-02293: cannot validate (...) - check constraint violated). Section "Adding a CHECK constraint to an existing table" covers your options.
Case sensitivity and string lists
String comparisons in a CHECK are case-sensitive, like everywhere else in Oracle SQL by default. status IN ('ACTIVE', 'INACTIVE') rejects 'active'. You can normalize the case in the condition, but then the stored value can still be lowercase:
-- Accepts 'active' and 'Active'; the stored value keeps its original case.
CHECK (UPPER(status) IN ('ACTIVE', 'INACTIVE'))If you want one canonical spelling in storage, keep the plain IN list and have the application, or a column default, supply the uppercase value.
For a list of allowed values that changes often, a CHECK list is a poor fit. Each change means altering the constraint. A small lookup table with a foreign key lets you add a value with an INSERT.
Several CHECK constraints on one column
A column may have any number of CHECK constraints. Oracle evaluates all of them, and the row must satisfy each one. Separate, named constraints give more precise error messages than one long combined condition:
ALTER TABLE products ADD CONSTRAINT products_price_max_ck
CHECK (list_price <= 100000);An insert with a price of 200000 now fails on products_price_max_ck, and the name states the rule that was broken.
Adding a CHECK constraint to an existing table
Use ALTER TABLE ... ADD CONSTRAINT. By default Oracle checks all existing rows before it accepts the constraint, so the statement fails if any current row violates it.
ALTER TABLE products ADD CONSTRAINT products_title_len_ck
CHECK (LENGTH(sku) >= 3);When legacy data violates the rule, you have these options:
- Fix the bad rows with
UPDATE, then add the constraint. - Add the constraint as
ENABLE NOVALIDATE. Oracle enforces it for new and changed rows, and skips the check of existing rows. - Add it as
DISABLE, clean the data, thenENABLEit.
ALTER TABLE products ADD CONSTRAINT products_title_len_ck
CHECK (LENGTH(sku) >= 3) ENABLE NOVALIDATE;With NOVALIDATE, old rows can stay invalid, but an UPDATE that touches one of them has to produce a valid row, or it fails. The details of the states are in a later chapter.
To remove a constraint, drop it by name:
ALTER TABLE products DROP CONSTRAINT products_title_len_ck;You cannot change the condition of an existing CHECK constraint. Drop it and add a new one with the same name. Between the two statements the rule is not enforced, so run both together, in a maintenance window if the table is busy.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `ORA-02290: check constraint (...) violated` | A row makes the condition false | Correct the value, or review whether the rule is right |
| `ORA-02293: cannot validate (...) - check constraint violated` | Existing rows break the new constraint | Clean the data, or use `ENABLE NOVALIDATE` |
| `ORA-02436: date or system variable wrongly specified in CHECK constraint` | The condition uses `SYSDATE` or a similar function | Use a trigger, or move the rule to the application |
| `ORA-02438: Column check constraint cannot reference other columns` | An inline constraint refers to a different column | Move it out of line |
| `ORA-02264: name already used by an existing constraint` | Constraint names are unique per schema | Pick another name, for example prefixed by the table |
Constraint names must be unique within a schema, not just within a table. Prefix them with the table name, as the examples do, to avoid collisions.
Inspecting CHECK constraints
The data dictionary view USER_CONSTRAINTS lists constraints. For CHECK constraints, constraint_type is C. The search_condition column holds the condition text.
SELECT constraint_name, search_condition, status, validated
FROM user_constraints
WHERE table_name = 'PRODUCTS'
AND constraint_type = 'C'
ORDER BY constraint_name;NOT NULL constraints also appear with type C, with conditions like "SKU" IS NOT NULL. Those rows are not a mistake. Oracle stores a NOT NULL as a special check constraint. Filter them out with search_condition_vc NOT LIKE '%IS NOT NULL' on Oracle 12.2 and later, if you only want the validation rules.
Design guidance
- Put in
CHECKonly rules that hold for every row at every moment, and that can be decided from that row alone. - Name every constraint. Include the table name and a suffix such as
_ck. - Add
NOT NULLwhen a column must have a value, sinceCHECKallowsNULL. - Keep each constraint small and single-purpose so the error message points to one rule.
- Use a foreign key, not a
CHECKwith a hard-coded list, when the allowed values are business data that changes. - Remember that constraints cost a small amount of work on each
INSERTandUPDATE. For simple conditions the cost is negligible compared with the data quality it protects.
Exercise
A table has the column quantity NUMBER CHECK (quantity > 0). A developer inserts a row with quantity set to NULL. Does the insert succeed? What change makes the insert fail, and why does the original constraint behave this way?
Show answer
The insert succeeds. A CHECK constraint rejects a row only when its condition is FALSE. With a NULL quantity, quantity > 0 evaluates to UNKNOWN, so the row passes. Adding NOT NULL to the column, for example quantity NUMBER NOT NULL CHECK (quantity > 0), makes the insert fail, because NOT NULL rejects the missing value.
Exercise
You want a rule that a new row's hire_date must not be in the future. Why does ALTER TABLE employees ADD CONSTRAINT emp_hire_ck CHECK (hire_date <= SYSDATE) fail, and what is one alternative?
Show answer
Oracle does not allow SYSDATE in a CHECK condition, and raises ORA-02436. The result of SYSDATE changes over time, so a stored row could become invalid without being modified, and the constraint could not be re-validated reliably. One alternative is a BEFORE INSERT OR UPDATE trigger that raises an error when :NEW.hire_date > SYSDATE. Another is validating the date in the application.
Exercise
A legacy table holds some rows with a negative salary. You must add CHECK (salary >= 0) today without fixing those rows. Write the statement and state what it enforces.
Show answer
ALTER TABLE employees ADD CONSTRAINT employeessalaryck CHECK (salary >= 0) ENABLE NOVALIDATE; The constraint is enforced for every new insert and for every update of a row, so new or changed rows must have a salary that is NULL or at least 0. Existing rows with negative salaries are not checked when the constraint is added, so they remain until they are corrected.