Introduction to IF NOT EXISTS in SQL SERVER

IF NOT EXISTS is a keyword to check for the existence of a specific record in a table with the condition set in the where clause of the query used inside this function. This keyword is used to check for specific data if it exists and if not exist the same data can be inserted in the same table. So this keyword ‘If Not Exist’ is helpful to avoid duplication of data in a table and insert unique data only.

There are 3 methods through which we can Insert data using the NOT EXISTS method. Below are the 3 approaches available in SQL Server.

  1. IF NOT EXISTS then INSERT.
  2. INSERT … Where NOT EXISTS.
  3. Using MERGE … INSERT.

We will see in detail these 3 approaches to Inserting data into a table when the data does not exist already.

How to Insert If Not Exists in SQL SERVER?

Adding Data to a table in SQL Server is a key operation. Data can be inserted into tables using many different scenarios like plain data inserted into a table without checking anything or checking if data already exists in the target table and only if the data does not exist then the new data is inserted. There are many methods to check the data if it exists like IF EXISTS, IF NOT EXISTS, or using the WHERE clause.

In this article, we will discuss the ‘IF NOT EXISTS’ alternative to check and insert a row of data into a table or to bulk insert data into a table.

Similar Reads

Introduction to IF NOT EXISTS in SQL SERVER

IF NOT EXISTS is a keyword to check for the existence of a specific record in a table with the condition set in the where clause of the query used inside this function. This keyword is used to check for specific data if it exists and if not exist the same data can be inserted in the same table. So this keyword ‘If Not Exist’ is helpful to avoid duplication of data in a table and insert unique data only....

Ways to Insert If Not Exists in SQL SERVER

Method 1: IF NOT EXISTS then INSERT...

Conclusion

Inserting data after checking if data exists is a key method to insert data and avoid duplicate data in tables. The ‘IF NOT EXISTS’ is one method to insert data after checking if a specific record already exists in a table. Also, when we need to copy and insert data from one table to another table by checking the existing data using NOT EXISTS option in the ‘WHERE’ clause of the SELECT query, which will check and avoid any duplicate data when transferring data from one table to another....