🧩 How to Fix ORA-00001: Unique Constraint Violated


🧩 Introduction:

The ORA-00001 error occurs when an attempt is made to insert a duplicate value into a column that has a unique constraint. This is common when handling primary keys, unique indexes, or business rules that enforce uniqueness. Resolving this error is critical to maintain data integrity in Oracle databases.


Step 1: Identify the Constraint

Check which constraint is being violated:


SELECT constraint_name, table_name, column_name

FROM all_cons_columns

WHERE table_name = 'MY_TABLE';


➡️ Replace MY_TABLE with the table in question. This helps identify the unique or primary key constraint causing ORA-00001.


Step 2: Review the Data Being Inserted

Before inserting, check whether the value already exists:


SELECT *

FROM my_table

WHERE unique_column = 'VALUE_TO_INSERT';


Step 3: Handle Duplicate Values


Option 1: Skip Duplicates

Use MERGE statement or INSERT ... SELECT with WHERE NOT EXISTS:



INSERT INTO my_table (id, name)

SELECT 101, 'John Doe'

FROM dual

WHERE NOT EXISTS (

  SELECT 1 FROM my_table WHERE id = 101

);


Option 2: Update Existing Record

If a duplicate exists, update the existing row instead of inserting:



MERGE INTO my_table t

USING (SELECT 101 AS id, 'John Doe' AS name FROM dual) s

ON (t.id = s.id)

WHEN MATCHED THEN

  UPDATE SET t.name = s.name

WHEN NOT MATCHED THEN

  INSERT (id, name) VALUES (s.id, s.name);


Step 4: Example Scenario

A developer attempts:


INSERT INTO EMPLOYEES (EMP_ID, NAME) VALUES (1001, 'Alice');


If EMP_ID = 1001 already exists, ORA-00001 occurs. Using MERGE or checking existence before insert resolves the issue without errors.


Step 5: Preventive Measures


Always validate input data for uniqueness.


Use sequences for primary keys instead of manual values.


Implement error handling in PL/SQL to catch duplicates gracefully.



Conclusion:

ORA-00001 errors indicate a violation of unique constraints. By identifying the constraint, checking existing data, and using MERGE statements or proper error handling, developers and DBAs can ensure data integrity and avoid insertion failures.

Comments