Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use multiple columns for a not in query?

Tags:

syntax

sql

mysql

I recently saw someone post this as part of an answer to an SO query question:

SELECT DISTINCT a, b, c 
FROM t1 
WHERE (a,b,c) NOT IN 
   ( SELECT DISTINCT a,b,c FROM t2 )

I'm a bit confused, as I always thought that you can't use multiple columns for "NOT IN" ("where(a,b,c)", etc.). Is this correct SQL syntax? And how about MySQL?

like image 976
froadie Avatar asked Feb 12 '10 14:02

froadie


People also ask

Can we use multiple columns in where clause?

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

Can multiple columns be compared between outer and inner query?

Multiple columns values of the inner query compared with multiple columns values of the outer query is called Multiple Column Subquery in Oracle.


2 Answers

Googling it suggests that it will work on some databases but not others. You can use this instead:

SELECT DISTINCT a, b, c 
FROM t1 
WHERE NOT EXISTS
   (SELECT 1 FROM t2 
    WHERE t1.a = t2.a AND t1.b = t2.b AND t1.c = t2.c)
like image 139
Corey Avatar answered Oct 22 '22 02:10

Corey


It's a SQL extension. Oracle, PostgreSQL and MySQL have it. SQL Server 2005 does not have it. I'm not sure about others.

like image 29
Vinko Vrsalovic Avatar answered Oct 22 '22 02:10

Vinko Vrsalovic