We help IT Professionals succeed at work.

How to check if a record already exists before inserting a new one

I'm looking for a simple clean way to make an MS SQL statement that selects all of column1 and column2 from one table, and inserts them into another table as new records, but only if the values for both column1 and column2 do not already exist in the table the insertion is being attempted on. Essentially, I do not want any duplication of values where the value of either column1 OR column2 must contain a unique value, but both do not need to be unique. Hope this is an easy one. Thanks.
Comment
Watch Question

Most Valuable Expert 2011
Top Expert 2012

Commented:
best way is to put a unique constraints/indexes on the table.

then simply insert the rows and capture exception on duplicates.
you can either ignore or report the attempt as needed.
SQL Server Data Dude
Most Valuable Expert 2013
Author of the Year 2015
Commented:
Rename the obvious, and give this a whirl..
INSERT INTO target_table (Column1, Column2) 
SELECT s.Column1, s.Column2
FROM source_table s
  -- LEFT means make sure you have all rows in s ...
  LEFT JOIN target_table t ON s.Column1 = t.Column1 AND s.Column2 = t.Column2
-- ... where there is no match in the target table for both columns
WHERE t.Column2 IS NULL 

Open in new window

Arnold LayneDeveloper

Author

Commented:
Hi sdstuber. I was hoping to not raise any exceptions at all. Is there one semi complex SQL statement that can accomplish this without errors?
Most Valuable Expert 2011
Top Expert 2012
Commented:
yes - you can, using something like Jim Horn posted.

The downside is the multiple accesses on the table means extra IO.
The upside is triggers on tables can be avoided which could mean less IO.
Arnold LayneDeveloper

Author

Commented:
I saw this which looks like it might do what I want. Does anybody know about this and will it work?
INSERT INTO table ( column1, column2, column3 )
   (
    SELECT $column1, $column2, $column3
     WHERE NOT EXISTS (
       SELECT 1
         FROM table
        WHERE column1 = $column1
          AND column2 = $column2
          AND column3 = $column3 )
    )

I think it's clo9se to what I want but it might not do exactly what I want. I don't fully understand it.
Jim HornSQL Server Data Dude
Most Valuable Expert 2013
Author of the Year 2015

Commented:
Let us know if you're interested in trying the solution I posted, as I've used it in multiple projects, and can attest that it meets the requirements as stated in this question.
PortletPaulEE Topic Advisor
Most Valuable Expert 2014
Awarded 2013
Commented:
>>"I think it's clo9se to what I want but it might not do exactly what I want. I don't fully understand it."

That is a very simple query using a method to test if there already is data matching 3 parameters

It is an alternative method to that proposed by Jim.

---------
You should become familiar with EXISTS
Arnold LayneDeveloper

Author

Commented:
Thanks guys.