USING EXISTS STATEMENT IN MSSQL

In Microsoft SQL Server (MSSQL), the EXISTS statement is used to test whether a subquery returns any rows.

The EXISTS statement in SQL Server is commonly used in various scenarios. Here are some use cases where EXISTS is frequently employed:

Use case 1: Checking for the Existence of Records:

Use EXISTS to check whether there are any records that satisfy a certain condition.

Syntax:-
Example:-

As an example, from AdventureWorks2019 database, in Sales table,

Result:-

Executing the query will give the following result.

Usecase 2: Correlated Subqueries:

Utilize EXISTS in correlated subqueries to check for the existence of related records.

Syntax:
Example:

The following SQL lists all products where exists a sales order which has a line total greater than 10k

Result:

Executing the query will result in

Usecase 3: Conditional Inserts or Updates:

Use EXISTS to conditionally insert or update records based on whether certain conditions are met.

Syntax:
Example:

Let’s create a dummy table and try to insert into this table only when a certain condition exists.

Result:

The above query inserts Product data into the SpecialOffers_Dummy table when we have Line Total > 25000

Usecase 4: Deleting Records Conditionally:

Use EXISTS to conditionally delete records based on certain criteria.

Syntax:
Example:

We can use the same dummy table created for the previous example.

Let’s say we want to delete the products which are in Silver color.

So we need to see if we have any products that exists in the Products table which are in silver color and that matches with our list of products in SpecialOffers_dummy table and delete them.

The following code is used to do the same.

Result:

The result of the query deletes the Product which is in silver color

Usecase 5: Using NOT EXISTS:

Similar to EXISTS, we can also use NOT EXISTS to check for the absence of records that meet certain conditions.

Syntax:
Example:

We can take all the 4 examples listed above and do the same with NOT EXISTS.

Result:

Conclusion:-

  • These are just a few use cases, and the EXISTS statement can be applied in various other scenarios depending on the specific requirements of your queries and data manipulation tasks in SQL Server.
  • In real time query writingEXISTS and NOT EXISTS becomes very handy as most of the time, we need to check for certain conditions before performing any operations in the data.

Popular posts