IF EXISTS is similar like IF condition.

In IF EXISTS we provide the select statement, if select statement return the row then IF EXISTS consider it as True and if select statement not return row then IF EXISTS consider it as False.


Below is the syntax of IF EXISTS.


Syntax for IF EXISTS

IF EXISTS ( < select statement from table > )
BEGIN
    < if statements >
END
ELSE
BEGIN
    < else statements >
END

Consider the below result for example.

multiple if condition result set

1) Example

Check that if any student of 10th std. belong from Pune city or not using IF EXISTS in SQL server.

Example

IF EXISTS ( SELECT * FROM tblStudentMaster WHERE City = 'Pune' AND Std = 10)
BEGIN
    SELECT 'Yes' AS 'Result'
END
ELSE
BEGIN
    SELECT 'No' AS 'Result'
END

Output

if else example in sql server


Note : When exactly use IF EXISTS statement in SQL Server?
Ans : It is similar like IF statement. We use IF EXISTS when we want to check row availability in table or need to check if any object is available in SQL Server or not.
We can also perform same action using IF condition but IF EXISTS remove the load of writing multiple lines.

2) Example

Another practical example of IF EXISTS in SQL Server.


Example

IF EXISTS ( SELECT * FROM tblStudentMaster WHERE City = 'Goa' )
BEGIN
    DELETE FROM tblStudentMaster WHERE City = 'Goa'
END
SELECT * FROM tblStudentMaster

Output

multiple if statements example in sql server


3) Example

IF NOT EXISTS example, in below example we have to check that if Rajesh student is available in system then update city as 'Delhi' else insert new record.


Example

IF NOT EXISTS ( SELECT * FROM tblStudentMaster WHERE StudentName = 'Rajesh' )
BEGIN
    INSERT INTO tblStudentMaster (StudentName, Std, City)
    VALUES ('Rajesh', 10, 'Delhi')
END
ELSE
BEGIN
    UPDATE tblStudentMaster SET City= 'Delhi' StudentName WHERE StudentName= 'Rajesh'
END

SELECT * FROM tblStudentMaster

Output

if not exists example in sql server