EXISTS Operator in SQL

Dotnetkida: Exists Operator

EXISTS Operator in SQL

The EXISTS operator is used to check the existence, it is a logical operator that returns true or false only.
We can use them within IF or Sub Queries.


USING WITH IF :


IF EXISTS (
              SELECT [ COLUMN_NAME ]
              FROM [ TABLE_NAME ]
              WHERE [ COLUMN_NAME ] IS NOT NULL
              )
BEGIN
       --QUERY TO DO ( SELECT [ID] FROM [TABLE_NAME] WHERE [ COLUMN_NAME ] IS NOT NULL)
END

USING WITH SUB QUERY :

SELECT [ID]

FROM [TABLE_NAME]

WHERE EXISTS (

              SELECT [ COLUMN_NAME ]

              FROM [ TABLE_NAME ]
              WHERE [ COLUMN_NAME ] IS NOT NULL
              )

Note: when we are using EXISTS operator in sub query, it will return true even when the sub query return NULL, as showing below in example :

SELECT [ COLUMN_NAME ]
FROM [ TABLE_NAME ]
WHERE EXISTS (
              SELECT NULL
              )


In the above query EXISTS will return true and query will return all data without any condition or filter.

Post a Comment

1 Comments

  1. Thanks for sharing!! Can you write something about exception handling in procedures ?

    ReplyDelete