This site is currently read-only as we are migrating to Oracle Forums for an improved community experience. You will not be able to initiate activity until January 30th, when you will be able to use this site as normal.

    Forum Stats

  • 3,890,054 Users
  • 2,269,775 Discussions


Issue while inserting records with union of select statements records

user11282491 Member Posts: 6
edited Mar 21, 2014 11:54AM in SQL & PL/SQL


I have a siuation with the below example. I have table like this

create table t1(col 1 interger , col2 primary key, col3)

Now im trying to insert data into using union of multiple select statments and my query goes like this

insert into t1(col1, col2,col3)

select seqname.nexval,A,B from

(select A, B from TT1


Select A, B from T2


Select A, B from T3)

As I know union should remove duplicates and my insert statement should work fine without any duplicates. But rurnning the above query is giving unique constraint voilated error. So can anybody suggest where my assumption is going wrong



  • Paul  Horth
    Paul Horth London, UKMember Posts: 3,402 Gold Trophy
    edited Mar 21, 2014 10:22AM

    select 1 A, 2 B from dual


    select 2 A, 2 B from dual;

    notice something? You get both rows, with B having the value 2 in both - and if B is the primary key....

    Union eliminates whole rows that are duplicates - not individual duplicate columns.

  • Frank Kulash
    Frank Kulash Boston, USAMember, Moderator Posts: 43,002 Red Diamond
    edited Mar 21, 2014 11:09AM


    As Paul said, UNION guarantees that the result set will not contain 2 identical rows; it says nothing about duplicate values in each column.  That is, UNION guarantees that, if 2 (or more) rows of its output have the same value for col2, then they will have different values for col1 and/or col3.  However, the primary key constraint will be violated if 2 (or more) rows have the same value from col2, no matter what is in col1 and col3.

    Also, if t1 has any data when you do the INSERT, some of the new rows may have the same col2 value as an existing row in t1, and that could cause the error.  You might want to use MERGE instead of INSERT in this case.

    What are the results you are looking for?  Post CREATE TABLE and INSERT statements for a little sample data for all the table involved (as the appear before the INSERT) and the results you want from that sample data (that is, the contents of t1 after the INSERT).  Test (and, if necessary, correct) the CREATE TABLE and INSERT statements before you post them.  Remember, you have to specify a datatype for each column.

    See the forum FAQ:

  • Hi Frank,

    Thanks for your reply. I have explained small part of my whole situation with some psuedo queries. I have a brand new table with no data existing prior to this insert statement. So I am stuck here to fill the table with union of this select queries..

This discussion has been closed.