Ошибка ora 00001 unique constraint

Have you gotten an “ORA-00001 unique constraint violated” error? Learn what has caused it and how to resolve it in this article.

Have you gotten an “ORA-00001 unique constraint violated” error? Learn what has caused it and how to resolve it in this article.

ORA-00001 Cause

If you’ve tried to run an INSERT or UPDATE statement, you might have gotten this error:

ORA-00001 unique constraint violated

This has happened because the INSERT or UPDATE statement has created a duplicate value in a field that has either a PRIMARY KEY constraint or a UNIQUE constraint.

There are a few solutions to the “ORA-00001 unique constraint violated” error:

  1. Change your SQL so that the unique constraint is not violated.
  2. Change the constraint to allow for duplicate values
  3. Drop the constraint from the column.
  4. Disable the unique constraint.

Solution 1: Modify your SQL

You can modify your SQL to ensure you’re not inserting a duplicate value.

If you’re using ID values for a primary key, it’s a good idea to use a sequence to generate these values. This way they are always unique.

You can use the sequence.nextval command to get the next value of the sequence.

So, instead of a query like this, which may not work if the employee_id value is already used:

INSERT INTO employee (employee_id, first_name, last_name)
VALUES (231, 'John', 'Smith');

You can use this:

INSERT INTO employee (employee_id, first_name, last_name)
VALUES (seq_emp_id.nextval, 'John', 'Smith');

Assuming the sequence is set up correctly, this should ensure that a unique value is used.

Find the constraint that was violated

The “ORA-00001 unique constraint violated” error usually shows a name of a constraint. This could be a descriptive name (if you’ve named your constraints when you create them) or a random-looking name for a constraint.

You can query the all_indexes view to find the name of the table and other information about the constraint:

SELECT *
FROM all_indexes
WHERE index_name = <constraint_name>;

This will give you more information about the specific fields and the table.

Solution 2: Change the constraint to allow for duplicates

If you have a unique constraint or primary key set up on your table, you could change the constraint to allow for duplicate values, to get around the ORA-00001 error.

Let’s say the unique constraint applies to first_name and last_name, which means the combination of those fields must be unique.

If you find that that rule is incorrect, you can change the constraint to say that the combination of first_name, last_name, and date_of_birth must be unique.

To do this, you need to drop and recreate the constraint.

To drop the constraint:

ALTER TABLE table_name
DROP CONSTRAINT constraint_name;

Then, recreate the constraint:

ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (col1, col2....);

Now your constraint will reflect your rules.

Solution 3: Remove the unique constraint

The third solution would be to drop the unique constraint altogether.

This should only be done if it is not required.

To do this, run the ALTER TABLE command:

ALTER TABLE table_name
DROP CONSTRAINT constraint_name;

The constraint will be removed and you should be able to UPDATE or INSERT the data successfully.

Solution 4: Disable the unique constraint

The final solution could be useful if you’re doing a lot of data manipulation and you need to temporarily disable the constraint, with the aim of enabling it later.

Disabling the constraint will leave it in the data dictionary and on the table, with the same name, it just won’t be checked when data is inserted or updated.

To disable the constraint:

ALTER TABLE table_name
DISABLE CONSTRAINT constraint_name;

If you need to enable the constraint in the future:

ALTER TABLE table_name
ENABLE CONSTRAINT constraint_name;

So, that’s how you can resolve the “ORA-00001 unique constraint violated” error.

Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

Problem

Error message running a stream exporting data to Oracle:
23000[1][520][ODBC Oracle Wire Protocol Driver][Oracle]ORA-00001: unique constraint (xxx) violated
(where xxx stands for the constraint name)

Cause

You tried to execute an INSERT or UPDATE statement that has created a duplicate value in a field restricted by a unique index.

Resolving The Problem

The option(s) to resolve this Oracle error are:
1) Drop the unique constraint.
2) Change the constraint to allow duplicate values.
3) Modify your SQL so that a duplicate value is not created.
If you are not sure which unique constraint was violated, you can run the following SQL:

SELECT DISTINCT table_name
FROM all_indexes
WHERE index_name = ‘xxx’; (where xxx stands for the constraint name from the error message)
Ref below url’s for more info:
https://docs.oracle.com/cd/E11882_01/server.112/e17766/e0.htm
http://www.techonthenet.com/oracle/errors/ora00001.php

So basically this issue happens if you attempt to insert an already existing value into a column defined as requiring unique data. You may have to check with your Oracle DBA and see if that constraint has been set and if so if it can be removed, as mentioned above, so the export can be completed. Either
way the issue is with the Oracle Database you are trying to write to and will have to be taken care of on the Oracle side

Related Information

[{«Product»:{«code»:»SS3RA7″,»label»:»IBM SPSS Modeler»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Modeler Server»,»Platform»:[{«code»:»PF025″,»label»:»Platform Independent»}],»Version»:»Not Applicable»,»Edition»:»»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

There’re only two types of DML statement, INSERT and UPDATE, may throw the error, ORA-00001: unique constraint violated. ORA-00001 means that there’s a constraint preventing you to have the duplicate value combination. Most likely, it’s an unique constraint. That’s why your INSERT or UPDATE statement failed to work.

Let’s see some cases.

1. INSERT

We inserted into a row that violate the primary key.

SQL> insert into employees (employee_id, last_name, email, hire_date, job_id) values (100, 'Chen', 'EDCHEN', to_date('17-JAN-22', 'DD-MON-RR'), 'AC_MGR');
insert into employees (employee_id, last_name, email, hire_date, job_id) values (100, 'Chen', 'EDCHEN', to_date('17-JAN-22', 'DD-MON-RR'), 'AC_MGR')
*
ERROR at line 1:
ORA-00001: unique constraint (HR.EMP_EMP_ID_PK) violated

In the error message, it told us that we specifically violate HR.EMP_EMP_ID_PK.

Please note that, not all primary keys are unique, it’s allowable to have non-unique primary keys.

2. UPDATE

We updated a row that violate an unique index.

SQL> update employees set email = 'JCHEN' where employee_id = 100;
update employees set email = 'JCHEN' where employee_id = 100
*
ERROR at line 1:
ORA-00001: unique constraint (HR.EMP_EMAIL_UK) violated

In the error message, it told us that we specifically violate HR.EMP_EMAIL_UK.

Solution

To solve ORA-00001, we should use a different value to perform INSERT INTO or UPDATE SET statement. The solution may sound easy to say, but hard to do, because we may not know what columns we violated.

Check Constraint Columns

So let’s see how we check unique columns.

SQL> column table_name format a20;
SQL> column column_name format a20;
SQL> select table_name, column_name, position from all_cons_columns where owner = 'HR' and constraint_name = 'EMP_EMAIL_UK';

TABLE_NAME           COLUMN_NAME            POSITION
-------------------- -------------------- ----------
EMPLOYEES            EMAIL                         1

The above query tells us that the column combination in the output is violated. To comply with the unique constraint, you can almost do nothing except for checking the existing row.

Drop Unique Constraint to Prevent ORA-00001

An alternative solution is to drop the unique index if it’s not necessary anymore. Dropping a primary or unique index needs more skills, otherwise you might see ORA-02429.

In a multithread environment, you may check whether the row is existing or not, then do your INSERT in order to prevent ORA-00001.

declare
  v_row_counts number;
begin
  select count(*) into v_row_counts from employees where employee_id = 100;
  if v_row_counts = 0 then
    -- Insert the row
  else
    -- Do not insert the row
  end if;
end;
/

In the above block of code, if the row count is 0, then we can do INSERT right after counting, elsewhere don’t do it.

ORA-00001 unique constraint violated is one of the common messages we often get while loading data.

ORA-00001 unique constraint violated

This ORA-00001 unique constraint violated error occurs when You tried to execute an INSERT or UPDATE statement that has created a duplicate value in a field restricted by a unique index.

We can perform the following action items for this ORA-00001

 (1) You can look at the error and find the constraint information with the below sql

SELECT column_name, position
FROM all_cons_columns
WHERE constraint_name = '<name of the constraint in error>'
AND owner = '<table owner>'
AND table_name = '<table name>'

Now we can check the existing data with the data we are inserting and then take action accordingly. You can change the keys so that they can be inserted

CREATE TABLE EXAMPLE_UNIQ(
EXAM_ID NUMBER NOT NULL ENABLE,
EXAM_NAME VARCHAR2(250) NOT NULL ENABLE
CONSTRAINT UK1_EXAMPLE UNIQUE (EXAM_ID, EXAM_NAME) ENABLE
);
table created.

INSERT INTO EXAMPLE_UNIQ (EXAM_ID, EXAM_NAME) VALUES (1000, 'XYZ');
1 rows inserted.
Commit;

INSERT INTO EXAMPLE_UNIQ (EXAM_ID, EXAM_NAME) VALUES (1000, 'XYZ');
SQL Error: ORA-00001: unique constraint (UK1_EXAMPLE) violated
Solution
INSERT INTO EXAMPLE_UNIQ (EXAM_ID, EXAM_NAME) VALUES (1001, 'XYZ');
1 rows inserted.

(2)  We can drop the constraint if duplicates are allowed in the table

Example

alter table <table name> drop constraint <constraint name>;

(3) The 11gr2 hint ignore_row_on_dupkey_index allows the statement to silently ignore ORA-00001 errors.

ORA-00001 unique constraint violated

  • The IGNORE_ROW_ON_DUPKEY_INDEX hint are unlike other hints in that they have a semantic effect. The general philosophy explained in “Hints” does not apply for these three hints.
  • The IGNORE_ROW_ON_DUPKEY_INDEX hint applies only to single-table INSERT operations. It is not supported for UPDATE, DELETE, MERGE, or multitable insert operations. IGNORE_ROW_ON_DUPKEY_INDEX causes the statement to ignore a unique key violation for a specified set of columns or for a specified index. When a unique key violation is encountered, a row-level rollback occurs and execution resumes with the next input row. If you specify this hint when inserting data with DML error logging enabled, then the unique key violation is not logged and does not cause statement termination.

The semantic effect of this hint results in error messages if specific rules are violated:

  • If you specify index, then the index must exist and be unique. Otherwise, the statement causes ORA-38913.
  • You must specify exactly one index. If you specify no index, then the statement causes ORA-38912. If you specify more than one index, then the statement causes ORA-38915.
  • You can specify either a CHANGE_DUPKEY_ERROR_INDEX or IGNORE_ROW_ON_DUPKEY_INDEX hint in an INSERT statement, but not both. If you specify both, then the statement causes ORA-38915.
  • As with all hints, a syntax error in the hint causes it to be silently ignored. The result will be that ORA-00001 will be caused, just as if no hint were used.
insert /*+ ignore_row_on_dupkey_index(unique_table, unique_table_idx) */
into
unique_table
(select * from non_unique_table);

Related articles

ORA-00911: invalid character
ORA-03113: end-of-file on communication channel
ORA-00257
ORA-29285: file write error
ORA-29913 with external tables
delete query in oracle
https://docs.oracle.com/cd/E11882_01/server.112/e17766/e0.htm

Reader Interactions

oracle tutorial webinars

ORA-00001 Error Message

Error messages in Oracle can seem like nagging roadblocks, but some are truly designed and signaled to aid in the efficiency of the database. While this may seem counterintuitive, if the program simply allowed the user to have free reign in making mistakes, Oracle would not be the dynamic and streamlined database software that it is known as. The ORA-00001 error message is indicative of this pattern of thinking.

The ORA-00001 message is triggered when a unique constraint has been violated. Essentially the user causes the error when trying to execute an INSERT or UPDATE statement that has generated a duplicate value in a restricted field. The error can commonly be found when a program attempts to insert a duplicate row in a table.

Before we progress to resolving the issue, it would be ideal to have some more information about the error. If you are unsure as to which constraint was violated to trigger the ORA-00001, there is an SQL statement that you can run to find out more about it. You can type the following command in:

SELECT DISTINCT table_name
FROM all_indexes
WHERE index_name = 'CONSTRAINT_NAME' ;


The constraint name can be found by looking at the error message itself. In parenthesis following the ORA-00001 notice, the constraint should be listed. This process will then return the name of the table that features the violated constraint.

Now that we know the constraint and table in question, we can move forward with fixing the problems itself. There are a few basic options. You can modify the SQL so that no duplicate values are created, thus no errors are triggered. If you do not wish to do this, you can also simply drop the table constraint altogether. This would only be recommended if the constraint is unnecessary for the foundation of your table.

Another option would be to modify the constraint so that it can allow duplicate values in your table. Depending on your version of Oracle, this can be done multiple ways. The first and universal method would be to manually adjust the constraint. However, if you’re using Oracle 11g or newer, you can use the ignore_row_on_dupkey_index hint. This feature will allow for insert SQL’s to enter as duplicates and be effectively ignored so that an ORA-00001 message will not be triggered.

By employing hints such as this, the ORA-00001 error can be sidestepped in many circumstances. A trigger method can also be a preventative approach to minimizing the frequency of ORA-00001 errors. These types of automatic increment columns can overwrite the value from an ID by inserting a value from the sequence in its place. On a more broad scale, remaining knowledgeable of the types of constraints that you are working with will help not only in preventing an error, but by also allowing you to respond to it quickly when it does occur. If you are unsure about some of the constraints on your tables or would like to know more about the most up-to-date versions of Oracle that include favorable hints the ignore_row_on_dupkey_index, it may be a good idea to speak with your licensed Oracle consultant for more information.

Oracle raises ORA-00001 error when an unique constraint is violated by a INSERT or UPDATE statement that attempts to insert
a duplicate key. SQL Server raises error 2627 in this case.

Last Update: Oracle 11g R2 and Microsoft SQL Server 2012

Unique Constraint Violation in Oracle

Assume there is a table with the primary key in Oracle:

Oracle:

   CREATE TABLE states
   (
      id CHAR(2) PRIMARY KEY,
      name VARCHAR2(90)
   );
 
   -- Let's insert a row
   INSERT INTO states VALUES ('MO', 'Missouri');
   # 1 row created.

Now let’s try to insert a row that violates the unique constraint enforced by the primary key:

Oracle:

   -- Assign MO instead of MT abbreviation to Montana by mistake 
   INSERT INTO states VALUES ('MO', 'Montana');
   # ERROR at line 1:
   # ORA-00001: unique constraint (ORA.SYS_C0014290) violated

You can see that ORA-00001 error is raised when an unique constraint is violated in Oracle.

Unique Constraint Violation in Microsoft SQL Server

Now let’s create the same table with the primary key in SQL Server:

SQL Server:

   CREATE TABLE states
   (
      id CHAR(2) PRIMARY KEY,
      name VARCHAR(90)
   );
 
   -- Let's insert a row
   INSERT INTO states VALUES ('MO', 'Missouri');
   # 1 row created.

Now we will try to insert a row that violates the unique constraint enforced by the primary key:

SQL Server:

   -- Assign MO instead of MT abbreviation to Montana by mistake 
   INSERT INTO states VALUES ('MO', 'Montana');
   # Msg 2627, Level 14, State 1, Line 1
   # Violation of PRIMARY KEY constraint 'PK__states__3213E83FFFE97CF5'. 
   # Cannot insert duplicate key in object 'dbo.states'.
   # The duplicate key value is (MO).

SQL Server raises error 2627 with the severity level 14 when a primary key is violated.

You can also call @@ERROR function to get the error code in SQL Server:

SQL Server:

  -- Get the error code of the last Transact-SQL statement
  SELECT @@ERROR
  # 2627

Resources

Oracle 11g Release 2 Documentation

Microsoft SQL Server 2012 — Books Online

SQLines Services

SQLines offers services to migrate Oracle databases and applications to Microsoft SQL Server. For more information, please Contact Us.

Вопрос:

Я пытаюсь вставить некоторые значения в таблицу через приложение и получить проблему ORA-00001: уникальное ограничение нарушено. Я вижу, что последовательности не синхронизированы с самым высоким идентификатором таблицы, но даже после исправления порядкового номера ошибка по-прежнему сохраняется. Как я могу отлаживать эту ошибку больше, делает ли журналы оракула больше ошибок? как я могу видеть журналы оракулов? Спасибо Priyank

update: мы используем плагин аудита аудита, а в классе домена для пользователя мы ловим событие сохранения и регистрируем запись в журнале аудита

Итак, в классе User мы делаем:

class User {

//some attributes, constraints, mappings

def onSave = {
Graaudit aInstance = new Graaudit();
aInstance.eventType= "GRA User Create"
aInstance.eventDescription = "GRA User Created"
aInstance.objectid = username
aInstance.objecttype = 'GRAUSER'
aInstance.user_id = RequestContextHolder.currentRequestAttributes().session.username

aInstance.withTransaction{
aInstance.save()
}
}

}

Если у нас нет вышеуказанного кода в событии onSave, пользователь будет создан успешно.
Я предполагаю, что он связан с транзакцией hibernate, которую мы используем на aInstance, который умирает или текущая транзакция умирает из-за этого сохранения.
Если мы не используем транзакцию, получаем исключение "org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" Не знаю, как исправить эту проблему.. Спасибо

Ответ №1

Сообщение об ошибке будет содержать имя ограничения, которое было нарушено (может быть более одного единственного ограничения в таблице). Вы можете использовать это имя ограничения для идентификации столбцов (столбцов), в которых объявляется уникальное ограничение

SELECT column_name, position
FROM all_cons_columns
WHERE constraint_name = <<name of constraint from the error message>>
AND owner           = <<owner of the table>>
AND table_name      = <<name of the table>>

Как только вы узнаете, какие столбцы (столбцы) затронуты, вы можете сравнить данные, которые вы пытаетесь использовать INSERT или UPDATE отношении данных, уже находящихся в таблице, чтобы определить, почему нарушается ограничение.

Ответ №2

Эта ошибка ORA возникает из-за нарушения уникального ограничения.

ORA-00001: уникальное ограничение (constraint_name) нарушено

Это вызвано попыткой выполнить инструкцию INSERT или UPDATE, которая создала дублирующее значение в поле, ограниченном уникальным индексом.

Вы можете решить это либо путем изменения ограничения, чтобы разрешить дубликаты, либо удалить уникальное ограничение, либо вы можете изменить свой SQL, чтобы избежать дублирования вставок.

Ответ №3

Сообщение об ошибке Oracle должно быть несколько дольше. Обычно это выглядит так:

ORA-00001: unique constraint (TABLE_UK1) violated

Имя в круглых скобках – это имя прохода. Он сообщает вам, какое ограничение было нарушено.

Ответ №4

Сообщение об ошибке выглядит следующим образом

Error message => ORA-00001: unique constraint (schema.unique_constraint_name) violated

ORA-00001 происходит, когда: “запрос пытается вставить” дублирующую “строку в таблицу”. Это накладывает уникальное ограничение на неудачу, следовательно, запрос не выполняется, и строка НЕ добавляется в таблицу. “

Решение:

Найти все столбцы, используемые в unique_constraint, например, столбец a, столбец b, столбец c, столбец d совместно создают unique_constraint, а затем найти запись из исходных данных, которая является дубликатом, используя следующие запросы:

-- to find <<owner of the table>> and <<name of the table>> for unique_constraint

select *
from DBA_CONSTRAINTS
where CONSTRAINT_NAME = '<unique_constraint_name>';

Затем используйте запрос Justin Cave (вставленный ниже), чтобы найти все столбцы, используемые в unique_constraint:

  SELECT column_name, position
FROM all_cons_columns
WHERE constraint_name = <<name of constraint from the error message>>
AND owner           = <<owner of the table>>
AND table_name      = <<name of the table>>

-- to find duplicates

select column a, column b, column c, column d
from table
group by column a, column b, column c, column d
having count (<any one column used in constraint > ) > 1;

Вы можете либо удалить эту дублирующую запись из ваших исходных данных (это был запрос на выборку в моем конкретном случае, как я испытал его с “Вставить в выборку”), либо изменить, чтобы сделать ее уникальной, или изменить ограничение.

Понравилась статья? Поделить с друзьями:
  • Ошибка p0453 hyundai
  • Ошибка openssl fatal
  • Ошибка null при входе на сервер майнкрафт
  • Ошибка p0451 subaru
  • Ошибка p0674 кайрон дизель