Sub topic 9
Constraint violations and how to read the errors
This chapter assumes you can write basic INSERT, UPDATE, and DELETE statements, know what primary key, foreign key, and NOT NULL constraints are, and can run SQL in SQL*Plus, SQL Developer, or SQLcl. It uses the dept_demo and emp_demo tables from the earlier chapters.
A constraint is a rule that the database enforces on every DML statement. When a statement would break a rule, Oracle rejects it with an error and undoes that statement. Reading these errors quickly is a core skill, because most failed DML in daily work comes from a small set of them.
How Oracle enforces constraints
Oracle checks constraints as part of running each DML statement. If any row in the statement breaks a rule, the whole statement fails and its changes are rolled back. This is called statement-level rollback. Work done by earlier statements in the same transaction is kept, and the transaction stays open.
That behavior matters for a batch of statements. If the third of five INSERTs fails, the first two remain pending until you COMMIT or ROLLBACK. You decide what happens to them.
Reading an Oracle error message
A constraint error has two parts: a number and a message that usually names the constraint.
ORA-00001: unique constraint (HR.SYS_C0012345) violatedORA-00001is the error code. Look it up or memorize the common ones.HRis the schema that owns the constraint.SYS_C0012345is the constraint name. When you do not name a constraint yourself, Oracle generates a name like this one, which tells you little.
Because generated names are hard to interpret, name your constraints in your own DDL. Compare these two table definitions.
CREATE TABLE emp_named (
emp_id NUMBER CONSTRAINT emp_named_pk PRIMARY KEY,
email VARCHAR2(80) CONSTRAINT emp_named_email_uk UNIQUE,
dept_id NUMBER CONSTRAINT emp_named_dept_fk REFERENCES dept_demo (dept_id)
);With this definition, a violation reports EMP_NAMED_EMAIL_UK, and you know which rule failed without any lookup.
The common errors
| Error | Meaning | Typical cause |
|---|---|---|
| ORA-00001 | Unique constraint violated | Inserting or updating to a key value that already exists |
| ORA-01400 | Cannot insert NULL | A NOT NULL column received no value |
| ORA-01407 | Cannot update to NULL | An UPDATE set a NOT NULL column to NULL |
| ORA-02290 | Check constraint violated | A value failed a CHECK rule |
| ORA-02291 | Integrity constraint violated, parent key not found | A child row points to a parent that does not exist |
| ORA-02292 | Integrity constraint violated, child record found | A parent row is deleted while child rows still reference it |
| ORA-12899 | Value too large for column | A string is longer than the column allows |
| ORA-01722 | Invalid number | A non-numeric string was converted to a number |
The sections below show the three that the learning objectives focus on, then the others briefly.
ORA-00001: unique constraint violated
A primary key or unique constraint allows each value only once. The error appears when an INSERT or UPDATE would create a duplicate.
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (1, 'Linus', 20, 8000);If employee 1 already exists, Oracle responds with:
ORA-00001: unique constraint (YOURSCHEMA.SYS_C0012345) violatedTo find out which columns the constraint covers, query the data dictionary. Use the constraint name from the message, in uppercase.
SELECT cc.table_name, cc.column_name, cc.position
FROM user_cons_columns cc
WHERE cc.constraint_name = 'SYS_C0012345'
ORDER BY cc.position;Replace the name with the one from your own error. For a constraint owned by another schema, use all_cons_columns and filter on owner as well.
Common fixes depend on intent:
- If the row already exists and you meant to change it, use UPDATE, or use MERGE as covered in the upsert chapter.
- If the key should be new, generate it from a sequence or an identity column instead of typing it.
- If the data is wrong, fix the source and rerun.
Note that a unique constraint allows multiple NULLs in a single-column key, because NULL is not equal to NULL. A primary key never allows NULL.
ORA-02291: parent key not found
A foreign key says that a child value must exist in the parent table. Inserting an employee into a department that does not exist breaks that rule.
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (3, 'Edsger', 99, 6500);ORA-02291: integrity constraint (YOURSCHEMA.SYS_C0012346) violated - parent key not foundThe row you are trying to write is the child. The parent is the row it refers to. Here no department 99 exists. The same error occurs on UPDATE if you change dept_id to a value with no parent.
Fix it by adding the parent row first, correcting the value, or setting the foreign key column to NULL if the design allows it. A NULL foreign key is not checked.
INSERT INTO dept_demo (dept_id, dept_name) VALUES (99, 'Research');
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (3, 'Edsger', 99, 6500);Order matters in multi-table loads. Insert parents before children.
ORA-02292: child record found
This is the mirror image. You try to remove or re-key a parent while children still point to it.
DELETE FROM dept_demo WHERE dept_id = 20;ORA-02292: integrity constraint (YOURSCHEMA.SYS_C0012346) violated - child record foundEmployee Ada belongs to department 20, so Oracle refuses. The message names the foreign key constraint, and that constraint lives on the child table. To find the child table, look up the constraint:
SELECT table_name, constraint_name, r_constraint_name
FROM user_constraints
WHERE constraint_name = 'SYS_C0012346';The table_name column shows the child table that holds the foreign key.
You have three ways forward:
- Delete or reassign the child rows first, then delete the parent.
- Declare the foreign key with
ON DELETE CASCADE, so deleting a parent deletes its children automatically. - Declare it with
ON DELETE SET NULL, so children stay but their key becomes NULL.
CREATE TABLE emp_cascade (
emp_id NUMBER PRIMARY KEY,
dept_id NUMBER CONSTRAINT emp_cascade_dept_fk
REFERENCES dept_demo (dept_id) ON DELETE CASCADE
);NOT NULL and CHECK violations
ORA-01400 happens when an INSERT leaves a NOT NULL column empty and the column has no DEFAULT. In emp_demo, emp_name is NOT NULL with no default.
INSERT INTO emp_demo (emp_id, dept_id, salary)
VALUES (4, 10, 5000);ORA-01400: cannot insert NULL into ("YOURSCHEMA"."EMP_DEMO"."EMP_NAME")This message names the column directly, which makes it easy to fix. Add the missing value to the column list. The column status is also NOT NULL, but it has DEFAULT 'ACTIVE', so omitting it is fine. Explicitly inserting NULL into status would still fail, because a DEFAULT applies only when the column is left out.
ORA-01407 is the UPDATE version: UPDATE emp_demo SET emp_name = NULL fails the same way.
ORA-02290 comes from CHECK constraints, such as a rule that salary must be positive:
ALTER TABLE emp_demo
ADD CONSTRAINT emp_demo_salary_ck CHECK (salary > 0);
UPDATE emp_demo SET salary = -1 WHERE emp_id = 1;ORA-02290: check constraint (YOURSCHEMA.EMP_DEMO_SALARY_CK) violatedA CHECK passes when its condition evaluates to NULL. A row with a NULL salary satisfies salary > 0, so add NOT NULL separately if NULL is not acceptable.
Data errors that look like constraint errors
Two more errors show up in the same places, although no constraint causes them:
- ORA-12899 means the value does not fit the column, for example a 60-character name in a
VARCHAR2(50)column. The message gives the actual and maximum lengths. - ORA-01722 means Oracle tried to convert text to a number and failed. In
INSERT ... SELECT, the conversion may happen on a row you did not expect, so check the source data.
Both appear in bulk loads, where one bad row can stop a whole statement.
Debugging workflow
When a DML statement fails, work through these steps:
- Read the error code and note whether it is a constraint error.
- Take the constraint name from the message, or the column name for ORA-01400.
- Look up the constraint in
user_constraintsanduser_cons_columns. - Find the offending value. For a multi-row statement, query the source data for duplicates or missing parents.
- Fix the data or the statement, then rerun.
For example, to find source rows whose parent department is missing before you load them:
SELECT s.emp_id, s.dept_id
FROM emp_stage s
WHERE s.dept_id IS NOT NULL
AND NOT EXISTS (SELECT 1
FROM dept_demo d
WHERE d.dept_id = s.dept_id);To find duplicate keys in a source before loading:
SELECT emp_id, COUNT(*)
FROM emp_stage
GROUP BY emp_id
HAVING COUNT(*) > 1;Edge cases
- Deferred constraints. A constraint declared
DEFERRABLE INITIALLY DEFERREDis checked at COMMIT, not at each statement. The error then appears on COMMIT, and Oracle rolls back the whole transaction. This is a surprise if you expect statement-level errors. - Multi-row statements. One bad row fails the entire statement. Rows processed before it are undone too. If you need the good rows to load anyway, use DML error logging, which a later chapter covers.
- Unique indexes. A unique index without a constraint raises the same ORA-00001, with the index name in the message.
- Updates that swap keys. An UPDATE that shifts several key values can fail partway even if the final state would be valid, depending on the order in which Oracle processes rows, unless the constraint is deferred.
Exercise
You run DELETE FROM dept_demo WHERE dept_id = 10; and get ORA-02292. Which table holds the foreign key that blocks the delete, and what are two ways to let the delete succeed?
Show answer
The foreign key is on the child table, here empdemo, because employee rows still reference department 10. Look up the constraint named in the message in userconstraints to confirm the table. To let the delete succeed, either delete or reassign the child rows first (for example, update their dept_id to another department or NULL), or recreate the foreign key with ON DELETE CASCADE or ON DELETE SET NULL.
Exercise
An INSERT into empdemo fails with ORA-02291 and names constraint SYSC0012346. Is the problem in the row you inserted or in another table, and how do you fix it?
Show answer
The inserted row is the child, and its deptid value has no matching row in the parent table deptdemo. Add the missing department first, or change deptid to an existing department. You can set deptid to NULL if the column allows it, because NULL foreign key values are not checked.
Exercise
A table has a column status VARCHAR2(10) DEFAULT 'ACTIVE' NOT NULL. Does INSERT INTO t (id, status) VALUES (1, NULL) succeed? Why or why not?
Show answer
It fails with ORA-01400. A DEFAULT is used only when the column is omitted from the INSERT. Explicitly supplying NULL overrides the default and violates the NOT NULL constraint.