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.
- IF NOT EXISTS then INSERT.
- INSERT … Where NOT EXISTS.
- 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.