Posts

Showing posts with the label Insert if not exists

Fastest way to perform an "Insert if not exists" operation

Image
Hi guys, As many of you know this blog was born with the main intent of talking about optimizations and performance . Today we see what is the fastest way to perform an operation that in reality often happens to perform. Let’s talk about "Insert if not exists" or insert new records in a table only if they are not already present. Ready to measure with your stopwatch in hand? Enjoy the reading!     The "Insert if not exists" operation Suppose you have a table which contains a list of all the products in our store whos name is  Products Suppose you have another table NewProducts , with the same structure, which also contains a list of products. What we want to do is to insert in the Products table all the products found in the NewProducts table that do not exist in the Products table . This is the structure of the two tables: CREATE TABLE PRODUCTS (ID INT IDENTITY (1,1), CODE VARCHAR (20) PRIMARY KEY CLUSTERED ([ID] ASC )) CREATE TABLE NEWPRODUCTS (ID INT IDENTITY (...