Hi Friends,
How can we use Exists keyword in Sql server with sub query ?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh TrivediPosted May 22, 2012, 11:39 PM
Exist is returns true if a subquery contains any rows.
for example:
SELECT a.Name, a.ID FROM Table1 AS a
WHERE EXISTS
(SELECT * FROM Employee AS b WHERE a.ID = b.ID);
This query return only those row which id present in employee table.
hope this will help u.
Satyapriya NayakPosted May 22, 2012, 9:33 PM
EXISTS simply tests whether the inner query returns any row. If it does, then the outer query proceeds. If not, the outer query does not execute, and the entire SQL statement returns nothing.
The syntax for EXISTS is:
SELECT "column_name1"
FROM "table_name1"
WHERE EXISTS
(SELECT *
FROM "table_name2"
WHERE [Condition])
Example
Table Store_Information
Table Geography
and we issue the following SQL query:
SELECT SUM(Sales) FROM Store_Information
WHERE EXISTS
(SELECT * FROM Geography
WHERE region_name = 'West')
We'll get the following result:
At first, this may appear confusing, because the subquery includes the [region_name = 'West'] condition, yet the query summed up stores for all regions. Upon closer inspection, we find that since the subquery returns more than 0 row, the EXISTS condition is true, and the condition placed inside the inner query does not influence how the outer query is run.
Please refer the below link
http://www.1keydata.com/sql/sql-exists.html
Thanks
Vikrant MorePosted May 22, 2012, 9:29 PM
abc_test contains 4 records and abc contains 6 records so with using EXISTS keywords it will gives me the 4 records which are exists in both table because both table have 3 records common plus 1 record from abc_test which is not in the table abc which is same as the left outer join.
select distinct id from abc_test
where exists
(
select distinct id from abc
)