Sub topic 14
Constraint states: ENABLE, DISABLE, VALIDATE and DEFERRABLE
This chapter assumes you can create tables with named constraints and use ALTER TABLE ... ADD CONSTRAINT, as covered in earlier chapters. You also need a schema on Oracle Database 12c or later where you can create tables. Every constraint has a state. The state controls whether Oracle checks new changes, whether Oracle has checked the existing rows, and when in a transaction the check happens.
The two independent state choices
A constraint state combines choices on three axes.
| Axis | Options | Question it answers |
|---|---|---|
| Enforcement | `ENABLE` or `DISABLE` | Does Oracle check changes made from now on? |
| Validation | `VALIDATE` or `NOVALIDATE` | Has Oracle verified the rows already in the table? |
| Timing | `NOT DEFERRABLE` or `DEFERRABLE` | Can the check wait until `COMMIT`? |
The defaults are ENABLE VALIDATE NOT DEFERRABLE. Oracle checks every change right away, and it checks the existing rows when you add the constraint.
The ENABLE/DISABLE and VALIDATE/NOVALIDATE choices combine into four useful states.
| State | New changes checked | Existing rows checked | Typical use |
|---|---|---|---|
| `ENABLE VALIDATE` | Yes | Yes (guaranteed) | Normal operation |
| `ENABLE NOVALIDATE` | Yes | No | Legacy data with known violations |
| `DISABLE NOVALIDATE` | No | No | Bulk loads, then fix later |
| `DISABLE VALIDATE` | No (changes are blocked) | Yes | Read-only guarantee on a table, mainly in data warehouses |
DISABLE VALIDATE is the odd one. For a unique or primary key constraint, Oracle guarantees that the existing data is valid by refusing any insert, update, or delete of the constrained columns. The table is effectively read-only for those columns.
Enabling and disabling constraints
Start with two small tables.
CREATE TABLE departments (
department_id NUMBER GENERATED ALWAYS AS IDENTITY,
department_name VARCHAR2(100) NOT NULL,
CONSTRAINT departments_pk PRIMARY KEY (department_id),
CONSTRAINT departments_name_uk UNIQUE (department_name)
);
CREATE TABLE employees (
employee_id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY
(START WITH 1000 INCREMENT BY 1 CACHE 20),
email VARCHAR2(255) NOT NULL,
salary NUMBER(10,2),
status VARCHAR2(10) DEFAULT 'ACTIVE' NOT NULL,
hire_date DATE DEFAULT SYSDATE NOT NULL,
department_id NUMBER,
CONSTRAINT employees_pk PRIMARY KEY (employee_id),
CONSTRAINT employees_email_uk UNIQUE (email),
CONSTRAINT employees_salary_ck CHECK (salary >= 0),
CONSTRAINT employees_status_ck CHECK (status IN ('ACTIVE', 'INACTIVE')),
CONSTRAINT employees_dept_fk FOREIGN KEY (department_id)
REFERENCES departments (department_id)
ON DELETE SET NULL
);Disabling a constraint stops Oracle from checking it. Enabling it again makes Oracle check the existing rows by default.
ALTER TABLE employees DISABLE CONSTRAINT employees_salary_ck;
INSERT INTO employees (email, salary) VALUES ('[email protected]', -50);
-- Fails with ORA-02293: cannot validate (EMPLOYEES_SALARY_CK) - check constraint violated
ALTER TABLE employees ENABLE CONSTRAINT employees_salary_ck;The ENABLE fails because the table now holds a row that breaks the rule. Oracle leaves the constraint disabled. You have two ways forward: fix the data, or enable the constraint without checking old rows.
ALTER TABLE employees ENABLE NOVALIDATE CONSTRAINT employees_salary_ck;After this, new inserts and updates are checked, but the row with -50 stays. Only rows you change later must satisfy the rule, and an update that touches the bad row without fixing it is rejected.
Effects on indexes
Primary key and unique constraints are enforced with an index. Oracle creates a unique index for them if none exists. When you disable the constraint, Oracle drops that index if it created it, and rebuilds it when you enable the constraint again. On a large table the rebuild takes time and space.
Disabling a primary or unique key that a foreign key references fails with ORA-02297. Disable the foreign keys first, or use CASCADE.
ALTER TABLE departments DISABLE CONSTRAINT departments_pk CASCADE;CASCADE disables the dependent foreign keys too. It does not re-enable them. After ENABLE CONSTRAINT departments_pk, you must enable each foreign key yourself.
Loading data with constraints off
A common pattern for bulk loads is to disable constraints, load, then enable them with validation.
ALTER TABLE employees DISABLE CONSTRAINT employees_dept_fk;
-- Bulk load happens here.
ALTER TABLE employees ENABLE VALIDATE CONSTRAINT employees_dept_fk;If validation fails, Oracle reports the error but does not say which rows are bad. You can find them with a query. For a foreign key, look for child rows whose parent is missing.
SELECT e.employee_id, e.department_id
FROM employees e
WHERE e.department_id IS NOT NULL
AND NOT EXISTS (SELECT 1
FROM departments d
WHERE d.department_id = e.department_id);Oracle can also record the offending rows for you. Create the EXCEPTIONS table with the script utlexpt1.sql (found under $ORACLE_HOME/rdbms/admin). Then name it in the ENABLE clause.
ALTER TABLE employees
ENABLE VALIDATE CONSTRAINT employees_salary_ck
EXCEPTIONS INTO exceptions;The failed statement still errors, but the EXCEPTIONS table now holds the ROWID of each violating row. The EXCEPTIONS INTO clause is deprecated in recent releases, so treat the manual query above as the dependable method.
Deferrable constraints
By default Oracle checks a constraint at the end of each statement. A DEFERRABLE constraint can instead be checked at COMMIT. This helps when rows depend on each other in a cycle, or when you load parent and child rows in any order.
There are two deferrable modes:
DEFERRABLE INITIALLY IMMEDIATE: checked after each statement, but you can switch to deferred for a transaction.DEFERRABLE INITIALLY DEFERRED: checked at commit, but you can switch to immediate.
Add a self-referencing manager column that is deferred.
ALTER TABLE employees ADD (manager_id NUMBER);
ALTER TABLE employees ADD CONSTRAINT employees_manager_fk
FOREIGN KEY (manager_id) REFERENCES employees (employee_id)
DEFERRABLE INITIALLY DEFERRED;Now you can insert an employee whose manager does not exist yet, as long as the manager exists by commit.
INSERT INTO employees (employee_id, email, manager_id)
VALUES (2001, '[email protected]', 2000);
INSERT INTO employees (employee_id, email)
VALUES (2000, '[email protected]');
COMMIT;If row 2000 were never inserted, the COMMIT would fail with ORA-02091 (transaction rolled back) and ORA-02291 (parent key not found). Oracle rolls back the whole transaction, not only the offending statement. That is the main trade-off. An error surfaces late, and you lose all the work in the transaction.
Switching timing inside a transaction
Use SET CONSTRAINT to change when a deferrable constraint is checked for the current transaction only.
SET CONSTRAINT employees_manager_fk IMMEDIATE;
SET CONSTRAINT employees_manager_fk DEFERRED;
SET CONSTRAINTS ALL DEFERRED;SET CONSTRAINT ... IMMEDIATE checks pending changes at once. If the data is invalid, the statement fails and the constraint stays deferred. This makes it a good way to test the state of your data before you commit. The setting lasts until the transaction ends, and then the constraint returns to its declared initial mode. You can also change a session-wide default with ALTER SESSION SET CONSTRAINTS = DEFERRED.
Rules and gotchas
- You cannot change a constraint between
DEFERRABLEandNOT DEFERRABLEwithALTER TABLE ... MODIFY CONSTRAINT. Drop and recreate it. - You can change
INITIALLY IMMEDIATEtoINITIALLY DEFERREDwithMODIFY CONSTRAINTonly if the constraint is already deferrable. - A deferrable primary key or unique constraint uses a non-unique index. That index is usually somewhat less efficient than a unique one.
NOT NULLis checked immediately, but you can declare it deferrable as aCHECK-like constraint. Most designs keep it immediate.ON DELETEactions such asSET NULLstill apply. Deferral changes only when the check of the key runs.
Changing state with MODIFY CONSTRAINT
You can change a state without dropping the constraint.
ALTER TABLE employees MODIFY CONSTRAINT employees_status_ck DISABLE;
ALTER TABLE employees MODIFY CONSTRAINT employees_status_ck ENABLE NOVALIDATE;
ALTER TABLE employees MODIFY CONSTRAINT employees_status_ck VALIDATE;The last statement changes only the validation. It checks the existing rows and marks the constraint VALIDATED. It fails if any row violates the rule.
Reading the state from the data dictionary
The USER_CONSTRAINTS view shows each axis in separate columns.
SELECT constraint_name,
constraint_type,
status,
validated,
deferrable,
deferred
FROM user_constraints
WHERE table_name = 'EMPLOYEES'
ORDER BY constraint_name;| Column | Values | Meaning |
|---|---|---|
| `STATUS` | `ENABLED`, `DISABLED` | Enforcement |
| `VALIDATED` | `VALIDATED`, `NOT VALIDATED` | Whether existing rows are known good |
| `DEFERRABLE` | `DEFERRABLE`, `NOT DEFERRABLE` | Whether timing can change |
| `DEFERRED` | `DEFERRED`, `IMMEDIATE` | The declared initial timing |
A constraint that shows ENABLED and NOT VALIDATED is the ENABLE NOVALIDATE state. During a review, filter on validated = 'NOT VALIDATED' or status = 'DISABLED' to find constraints that give weaker guarantees than they appear to.
Choosing a state
- Use
ENABLE VALIDATEfor ordinary tables. It is the strongest guarantee and the default. - Use
DISABLEthenENABLE VALIDATEaround a bulk load, and check for violations before users return. - Use
ENABLE NOVALIDATEonly when old data cannot be fixed now but new data must be clean. - Use
DEFERRABLEfor circular references or order-independent loading, and accept that errors appear atCOMMIT.
Exercise
The table orders has a check constraint ordersqtyck (qty > 0). A legacy row has qty = 0, and you cannot fix it this week. Write the statement that makes Oracle reject new bad data without failing on the legacy row, and say which STATUS and VALIDATED values USER_CONSTRAINTS will show afterward.
Show answer
ALTER TABLE orders ENABLE NOVALIDATE CONSTRAINT ordersqtyck; (or ALTER TABLE orders MODIFY CONSTRAINT ordersqtyck ENABLE NOVALIDATE;) USERCONSTRAINTS shows STATUS = ENABLED and VALIDATED = NOT VALIDATED. New inserts and updates are checked, and the legacy row stays until you fix it and run ALTER TABLE orders MODIFY CONSTRAINT ordersqty_ck VALIDATE.
Exercise
A transaction inserts a child row before its parent, and the foreign key is DEFERRABLE INITIALLY DEFERRED. The parent insert is forgotten. What happens at COMMIT, and how can you test for the problem before committing?
Show answer
The COMMIT fails with ORA-02091 and ORA-02291, and Oracle rolls back the whole transaction. Before committing, run SET CONSTRAINT constraint_name IMMEDIATE (or SET CONSTRAINTS ALL IMMEDIATE). It checks the pending changes at once and raises ORA-02291 if the parent is missing, and you can then insert the parent and commit.