Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL "Where not in" using two columns

Tags:

sql

tsql

I want to select all records from a table T1 where the values in columns A and B has no matching tuple for the columns C and D in table T2.

In mysql “Where not in” using two columns I can read how to accomplish that using the form select A,B from T1 where (A,B) not in (SELECT C,D from T2), but that fails in T-SQL for me resulting in "Incorrect syntax near ','.".

So how do I do this?

like image 832
Anders Lindén Avatar asked Jul 30 '12 07:07

Anders Lindén


People also ask

Can we use two columns in WHERE clause in SQL?

Answer. Yes, within a WHERE clause you can compare the values of two columns. When comparing two columns in a WHERE clause, for each row in the database, it will check the value of each column and compare them.

Can we use multiple columns in WHERE clause?

But the WHERE.. IN clause allows only 1 column.

What can I use instead of not in SQL?

An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.

Can we use in and not in together in SQL?

IN and NOT IN clause on the same column is legit and logical. It's just like doing Set Minus (Set A - Set B) . thus the result.


1 Answers

Use a correlated sub-query:

  ... 
WHERE 
  NOT EXISTS (
    SELECT * FROM SecondaryTable WHERE c = FirstTable.a AND d = FirstTable.b
  )

Make sure there's a composite index on SecondaryTable over (c, d), unless that table does not contain many rows.

like image 142
Tomalak Avatar answered Oct 22 '22 14:10

Tomalak