Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between INTERSECT and WHERE IN?

Tags:

sql

tsql

I have written and passed 70-433 (SQL 2008 MCTS exam) and was reviewing when I realised that I have been doing what INTERSECT does with a WHERE IN subquery, as well as EXCEPT with a WHERE NOT IN subquery.

Are there any differences between using the new commands instead of subqueries?

like image 832
callisto Avatar asked Jul 26 '10 13:07

callisto


2 Answers

INTERSECT and EXCEPT compare all the selected values in the rows returned while WHERE IN and WHERE NOT IN only compare one column at a time.

SELECT name,date from customers
EXCEPT
SELECT name, date from orders
like image 161
Kingo Avatar answered Oct 14 '22 00:10

Kingo


There is an important difference in how they handle NULLs

WITH T1 AS(SELECT 1 AS COL UNION SELECT NULL),
     T2 AS (SELECT 2 AS COL UNION SELECT NULL)
SELECT * FROM T1 
INTERSECT 
SELECT * FROM T2;

.

COL
-----------
NULL

(1 row(s) affected)

.

WITH T1 AS(SELECT 1 AS COL UNION SELECT NULL),
     T2 AS (SELECT 2 AS COL UNION SELECT NULL)
SELECT * FROM T1 WHERE COL IN (SELECT COL FROM T2) ;

.

COL
-----------

(0 row(s) affected)

.

WITH T1 AS(SELECT 1 AS COL UNION SELECT NULL),
     T2 AS (SELECT 2 AS COL UNION SELECT NULL)
SELECT * FROM T1 
EXCEPT 
SELECT * FROM T2;

.

COL
-----------
1

(1 row(s) affected)

.

WITH T1 AS(SELECT 1 AS COL UNION SELECT NULL),
     T2 AS (SELECT 2 AS COL UNION SELECT NULL)
SELECT * FROM T1 WHERE COL NOT IN (SELECT COL FROM T2);

.

COL
-----------

(0 row(s) affected)
like image 30
Martin Smith Avatar answered Oct 13 '22 23:10

Martin Smith