Problem : merge table return error: ORA-00001: unique constraint

Problem : merge table return error: ORA-00001: unique constraint

Hello,

I am trying to resolve ORA-00001: unique constraint (OCP.PK_MOVIES) violated error and don’t understand cause of this problem.

I have a table name =  movies:

sql> create table movies
(movie_name varchar2(30),
showtime varchar2(30))

alter table movies
add constraint pk_movies primary key(movie_name);

insert into movies values(‘GONE WITH THE WIND’,’8:00 PM’)
/

When I issue merge :

merge into movies M1
using movies m2 on (m2.movie_name = m1.movie_name
and m2.movie_name = ‘ABC NEWS’)
when matched then update set m1.showtime = ‘9:00 PM’
when not matched then insert (m1.movie_name, m1.showtime)
values (‘ABC NEWS’,’9:00 PM’)

table insert row succesfully.

when I execute the same merge command:

I get  ORA-00001: unique constraint  which makes sense because of the primary key. However, when i change the movie name in the 3rd line I still
get ORA-00001: unique constraint .

Can someone please tell me why Oracle is returning ora-0001 unique constraint error when I execute below code using merge command

merge into movies M1
using movies m2 on (m2.movie_name = m1.movie_name
and m2.movie_name = ‘XYZ NEWS’)
when matched then update set m1.showtime = ‘9:00 PM’
when not matched then insert (m1.movie_name, m1.showtime)
values (‘XYZ NEWS’,’9:00 PM’)
/


Solution: merge table return error: ORA-00001: unique constraint

there’s a problem in which you are trying to do the merge….
when you execute the below query

merge into movies M1
using movies m2 on (m2.movie_name = m1.movie_name
and m2.movie_name = ‘XYZ NEWS’)
when matched then update set m1.showtime = ‘9:00 PM’
when not matched then insert (m1.movie_name, m1.showtime)
values (‘XYZ NEWS’,’9:00 PM’);

see what happens internally…

the above “on” condition causes both the rows already present to represent mismatch. so it tries to insert same row twice and hence causes failure.

remove the primary key and execute the above statement again and see what happens.

alter table movies drop primary key;

SQL>merge into movies M1
using movies m2 on (m2.movie_name = m1.movie_name
and m2.movie_name = ‘XYZ NEWS’)
when matched then update set m1.showtime = ‘9:00 PM’
when not matched then insert (m1.movie_name, m1.showtime)
values (‘XYZ NEWS’,’9:00 PM’);

2 rows merged.

SQL>select * from movies;

MOVIE_NAME                     SHOWTIME
—————————— ———–
GONE WITH THE WIND             8:00 PM
ABC NEWS                       9:00 PM
XYZ NEWS                       9:00 PM
XYZ NEWS                       9:00 PM