How to store exceptions into a EXCEPTIONS table while adding constraint in oracle

Let's troubleshoot and ensure you're using EXCEPTIONS INTO correctly. Here’s a working example step-by-step, tested and compliant with Oracle behavior:


1. Create a table with duplicate data

CREATE TABLE test_emp (
  emp_id NUMBER,
  emp_name VARCHAR2(100)
);
INSERT INTO test_emp VALUES (1, 'Alice');
INSERT INTO test_emp VALUES (1, 'Bob');   -- Duplicate emp_id
INSERT INTO test_emp VALUES (2, 'Charlie');
COMMIT;

2. Create the EXCEPTIONS table (if not already present)

Run this script from Oracle:

@?/rdbms/admin/utlexcpt.sql

This will create a table named EXCEPTIONS in your schema.

Alternatively, manually:

CREATE TABLE exceptions (
  row_id     ROWID,
  owner      VARCHAR2(30),
  table_name VARCHAR2(30),
  constraint VARCHAR2(30)
);

3. Add the constraint with ENABLE NOVALIDATE

ALTER TABLE test_emp
ADD CONSTRAINT emp_id_uk UNIQUE(emp_id)
ENABLE NOVALIDATE;
if this is not working -- add the constraint with disabled status
ALTER TABLE test_emp ADD CONSTRAINT emp_id_uk UNIQUE (emp_id) DISABLE;  

This adds the constraint without checking existing data.


4. Validate the constraint and capture exceptions

ALTER TABLE test_emp
ENABLE VALIDATE CONSTRAINT emp_id_uk
EXCEPTIONS INTO exceptions;
This throws the following error but stores the exceptions into the EXCEPTIONS table.

ORA-00604: error occurred at recursive SQL level 1
ORA-06502: PL/SQL: numeric or value error
ORA-06512: at line 10
ORA-02299: cannot validate (FMS_ADMIN.EMP_ID_UK) - duplicate keys found

5. Check the exceptions table

SELECT * FROM exceptions;

You should now see the duplicate row(s) listed.


Post a Comment

And that's all there is to it!

If anyone has any other questions or requests for future How To posts, you can either ask them in the comments or email me. Please don't feel shy at all!

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

Previous Post Next Post