I’m trying to insert distinct values from one table into another. My target table has a primary key studentid and when I perform distinct id from source to target the load is successful. When I’m trying to load a bunch of columns from source to target including student_id, I’m getting an error unique constraint violated. There is only one constraint on target which is the primary key on studentid.
my query looks like this (just an example)
insert into target(studentid, age, schoolyear)
select distinct id, age, 2012 from source
Why does the above query returns an error where as the below query works perfectly fine
insert into target(studentid)
select distinct id from source
help me troubleshoot this.
Thanks for your time.
In your first query you are selecting for distinct combination of three columns ie,
Not the distinct id alone. In such case there are possibility for duplicate id’s.
For example, Your above query is valid for this
But in your second query you are selecting only distinct id’s
So this will return like,
In this case there is no way for duplicates and your insert into target will not
fail.
If you really want to do bulk insert with constrain on target then go for
any aggregate functions
Or if you dont want to loose any records from source to target then remove your constraint on target and insert it.
Hope this helps