Search code examples
sqlsql-servert-sqlcorrelated-subquery

SQL : Filtering with multiple columns in a subquery


I want to select all the rows from a table, those are not present in ID column of another table.

For example my Table1 has below structure :

C1  C2  C3
--  --  --
1   A   Z
2   B   Y
3   C   X

My Table2 Looks like :

    D1  D2  
    --  --  
    1   A   
    2   Y
    3   X

My working query looks something like :

slect * from Table1
where (C2 NOT IN (Select D2 from Table2);

This works fine, but if I want to filter on basis of combination of both the columns (i.e. D1 & D2, then I cant write the query as :

slect * from Table1
where ((C1,C2) NOT IN (Select (D1,D2) from Table2);

Can anyone help me rectify the above query?


Solution

  • Use NOT EXISTS:

    SELECT t.* from Table1 t
    WHERE NOT EXISTS
    (
        SELECT 1 FROM Table2 t2
        WHERE t.C1 = t2.D1
        AND   t.C2 = t2.D2
    )
    

    Result:

    C1  C2  C3
    2   B   Y
    3   C   X
    

    Here's a Demo: http://sqlfiddle.com/#!3/81fdd/4/0

    NOT EXISTS has lesss isues than NOT IN anyway:

    Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?