Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle Database. Insert a copy of a row to the same table (Duplicate key error message)

Tags:

sql

oracle

In Oracle database I have one table with primary key GAME_ID. I have to insert a copy of a row where game_name = 'Texas holdem' but it tells me:

An UPDATE or INSERT statement attempted to insert a duplicate key.

This is query I am using:

INSERT INTO GAME (SELECT * FROM GAME WHERE NAME = 'Texas Holdem');
like image 996
Mark2 Avatar asked Jan 03 '14 16:01

Mark2


People also ask

How do you avoid duplicate queries in SQL insert?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

What will happen if we try to insert the same set of data again into a table which has primary key in Rdbms?

If you attempt to insert a row with the same primary key as a previous row, you will get a SQL error (try it in the commented out code below). If you insert a row without specifying the primary key, then SQL will automatically pick one for you that's different from other values.

Which DML statement do we use to prevent duplicate rows from being inserted?

Using COUNT(*) = 0. To avoid duplicates, the COUNT or records returned by the subquery above should be zero.


2 Answers

Assuming your game_id is generated by a sequence, you can get a new as part of the select statement:

INSERT INTO GAME (game_id, name, col_3)
SELECT seq_game_id.nextval, name, col_3
FROM GAME 
WHERE NAME = 'Texas Holdem';
like image 152
a_horse_with_no_name Avatar answered Oct 26 '22 03:10

a_horse_with_no_name


Let me just offer a slightly more abstract point of perspective...

  • In a relational database, table is a physical representation of the mathematical concept of relation.
  • Relation is a set (of tuples, i.e. table rows/records).
  • A set either contains given element or it doesn't, it cannot contain the same element multiple times (unlike multiset).
  • Therefore, you can never have two identical rows in the table, and still call your database "relational".1

You can insert a similar row through, as other answers have demonstrated.


1 Although practical DBMS (including Oracle) will typically allow you to create a table without any key, making identical duplicates physically possible. However, consider it a big red flag if you ever find yourself doing that.

like image 42
Branko Dimitrijevic Avatar answered Oct 26 '22 03:10

Branko Dimitrijevic