SQL Server EXISTS Conditions

In SQL Server, EXIST condition is used in combination with a subquery. It returns at least one row after met the conditions. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Syntax:

WHERE EXISTS ( subquery );   

Parameter explanation

subquery: The subquery is a SELECT statement. If the subquery returns at least one record in its result set, the EXISTS clause will evaluate to TRUE and the EXISTS condition will be met. If the subquery does not return any records, the EXISTS clause will evaluate to FALSE and the EXISTS condition will not be met.

EXISTS condition with SELECT statement

We have two tables: “Employees” and “Employee2”, having the following data:

Employees:

SQL Exists conditions 1

Employee2:

SQL Exists conditions 2

Example:

Use the EXISTS condition on both tables with OR condition:

SELECT *  

FROM [javatpoint].[dbo].[Employees]  

WHERE EXISTS (SELECT *  

              FROM [javatpoint].[dbo].[Employee2]  

              WHERE Employees.salary = Employee2.salary  

              OR Employees.name = Employee2.name);

Output:

SQL Exists conditions 3

Example2:

Use the EXISTS condition on both tables with AND condition:

SELECT *  

FROM [javatpoint].[dbo].[Employees]  

WHERE EXISTS (SELECT *  

              FROM [javatpoint].[dbo].[Employee2]  

              WHERE Employees.salary = Employee2.salary  

              AND Employees.name = Employee2.name);

Output:

SQL Exists conditions 4

There is nothing common in both table on given parameters.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *