Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : check if all rows exists in other table

Tags:

sql-server

I need to know if all rows from one table exists in other:

declare @Table1 table (id int)
declare @Table2 table (id int)

insert into @Table1(id) values (1)
insert into @Table1(id) values (4)
insert into @Table1(id) values (5)


insert into @Table2(id) values (1)
insert into @Table2(id) values (2)
insert into @Table2(id) values (3)

if exists (select id from @Table1 where id in (select id from @Table2))
    select 'yes exists'
else
    select 'no, doesn''t exist' 

This query returns yes exists but should return no, doesn't exist because only 1 exists in @Table2, values 4 and 5 don't.

What should I change in my query? Thanks!

like image 842
ihorko Avatar asked Apr 27 '12 15:04

ihorko


2 Answers

IF NOT EXISTS (
    SELECT ID FROM @Table1
    EXCEPT
    SELECT ID FROM @Table2
)
SELECT 'yes exists'
ELSE SELECT 'no, doesn''t exist'
like image 149
John Dewey Avatar answered Sep 22 '22 00:09

John Dewey


You could use EXCEPT to get the set difference of both tables. If any ID's are returned, both tables are not equal:

SELECT ID
FROM @Table1
EXCEPT 
SELECT ID
FROM @Table2

EXCEPT returns any distinct values from the left query that are not also found on the right query.

So, to get your "no, doesnt exist":

;WITH diff AS(
    SELECT ID
    FROM @Table1
    EXCEPT 
    SELECT ID
    FROM @Table2
)
SELECT CASE WHEN COUNT(diff.ID) = 0 
         THEN 'yes exists'
         ELSE 'no, doesnt exist'
         END AS Result
FROM diff
like image 34
Tim Schmelter Avatar answered Sep 21 '22 00:09

Tim Schmelter