Here are 4 examples that illustrate when you will use IF EXISTS and when you will use IF NOT EXISTS:
A) Delete related records from more than one table:
IF EXISTS (SELECT TOP(1) 1 FROM Table 1 WHERE ORDER_ID = 11032) BEGIN DELETE FROM Table 1 WHERE ORDER_ID = 11032 DELETE FROM Table 2 WHERE ORDER_ID = 11032
B) Update a record in more than 1 table, if it exists:
IF EXISTS (SELECT TOP(1) 1 FROM Table 1 WHERE ORDER_ID = 11032) BEGIN UPDATE Table 1 SET Field1='X' WHERE ORDER_ID = 11032 UPDATE Table 2 SET Field2='Y' WHERE ORDER_ID = 11032
C) Insert a record into more than 1 table if it does not exist:
IF NOT EXISTS (SELECT TOP(1) 1 FROM Table 1 WHERE ORDER_ID = 11032) BEGIN INSERT INTO Table 1(Field1, Field2, ORDER_ID) VALUES ('A', 'B', 11032) INSERT INTO Table 2(Field3, Field4, ORDER_ID) VALUES ('X', 'Y', 11032)
D) Upsert (= insert or update) entry, depending on availability:
IF EXISTS (SELECT TOP(1) 1 FROM Table 1 WHERE ORDER_ID = 11032) BEGIN UPDATE Table 1 SET Field1='X' WHERE ORDER_ID = 11032
Instead of the above statement (case D), you can also use the new MERGE operator , but I think it is a little difficult to use.
NOTES:
- If only one table is affected, you will not use EXIST in any of the above examples except for the upsert D example.
- SELECT TOP (1) 1 FROM ... is more efficient, because it is interrupted after the 1st match is found, then it returns only number 1 (which is more efficient for selecting, for example, the NVARCHAR (max) field)
- You can see that only in example C) you are forced to use
IF NOT EXISTS(...) , all other examples use IF EXISTS(...) , which is more efficient.
Matt
source share