Sunday, June 10, 2007

SQL EXISTS

Using a subquery to test for the existence of rows.
If it Exists Operators return a row, then the outer query proceeds. If not, the outer query does not execute or return any result or row.

Below is Example for SQL EXISTS

Company

Sales($)

Website

Sql Traniner2500http://www.sqltutorials.blogspot.com
BeautyCentury3000http://beautycentury.blogspot.com
TravelYourself2800http://travelyourself.blogspot.com
Table1

Sales

Website

2900http://www.sqltutorials.blogspot.com
3000http://beautycentury.blogspot.com
2800http://travelyourself.blogspot.com
Table2

SQL EXISTS Statement


SELECT * FROM TABLE1 WHERE EXISTS(SELECT * FROM TABLE2) Result

Company

Sales($)

Website

Sql Traniner2500http://www.sqltutorials.blogspot.com
BeautyCentury3000http://beautycentury.blogspot.com
TravelYourself2800http://travelyourself.blogspot.com



- We also can using the EXISTS in IF...ELSE Statement to checking the existence of a row or value.
- If IF...ELSE return true, it will return the result of Sql statement inside the BEGIN and END.

IF EXISTS(SELECT * FROM TABLE1 WHERE Company='TravelYourself')
BEGIN
SELECT * FROM TABLE1 WHERE Company='TravelYourself'
END

Result
TravelYourself2800http://travelyourself.blogspot.com