This has to be wrapped in a transaction to avoid a race condition, though. Otherwise someone might insert a row between the time I check the table and when I insert the row. SQL Server insert if not exists best practice. The age-old technique and I suspect most common practice is doing a left join where the values are null from the table being inserted into.
NB: The code below is extracted from a stored procedure run by the update, insert and delete triggers on the WorkLog table. PersonID is one of the parameters to that table.
The stored procedure works fine if I comment out the second part of this statement. All this steps wrapped by a transaction. This is for a booking system, so it must be atomic and reliable.
It must return true if the transaction was committed and the flight booked. The following example finds rows in the DimCustomer table where the LastName and BirthDate do not match any entries in the ProspectiveBuyers table. NOT EXISTS works as the opposite as EXISTS.
Get an introduction to SQL with a course at Udemy. However, single line insert as I showed is probably better in high concurrency.
If all the records are not exist in the table then records are inserted successfully.