Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL difference between WHERE EXISTS and INTERSECT

Can you tell me what is the difference between these two? I have tried using both for comparing two tables, but the results are a bit different:

  SELECT a.CustID FROM tbl1 AS a 
  WHERE EXISTS (SELECT b.CustID FROM tbl2 b WHERE (a.CustID=b.CustID))

This query results 178 rows. However, the query below results in 162 rows.

  SELECT a.CustID FROM tbl1 AS a
  INTERSECT
  SELECT b.CustID FROM tbl2 AS b
like image 777
sqluser Avatar asked Jan 28 '18 05:01

sqluser


People also ask

When should the INTERSECT query be used?

The SQL INTERSECT operator is useful in several situations. It is best when you want to fetch common rows between the results of two select statements or queries.

What can I use instead of INTERSECT in SQL?

Although there is no INTERSECT operator in MySQL, you can easily simulate this type of query using either the IN clause or the EXISTS clause, depending on the complexity of the INTERSECT query. First, let's explain what an INTERSECT query is. An INTERSECT query returns the intersection of 2 or more datasets.

What is the difference between INTERSECT and INTERSECT all in SQL?

INTERSECT ALL is part of the SQL specification, but SQL Server doesn't care about it. The difference to the INTERSECT operator is very simple: INTERSECT ALL doesn't eliminate duplicate rows. The nice thing is that you can simulate an INTERSECT ALL in SQL Server.

What is the difference between INTERSECT and inner join in SQL?

They are very different, even in your case. The INNER JOIN will return duplicates, if id is duplicated in either table. INTERSECT removes duplicates. The INNER JOIN will never return NULL , but INTERSECT will return NULL .


1 Answers

Following query will result multiple rows if you have duplicate CustId in tbl1

  SELECT a.CustID FROM tbl1 AS a 
  WHERE EXISTS (SELECT b.CustID FROM tbl2 b WHERE (a.CustID=b.CustID))

In case if you use INTERSECT, duplicates will be eliminated

  SELECT a.CustID FROM tbl1 AS a
  INTERSECT
  SELECT b.CustID FROM tbl2 AS b

For example.

CREATE TABLE tbl1 (CustId int, CustName varchar(100))
GO
INSERT INTO tbl1 VALUES(1 ,'N1')
GO
INSERT INTO tbl1 VALUES(2 ,'N2')
GO
INSERT INTO tbl1 VALUES(1 ,'N3')
GO
CREATE TABLE tbl2 (CustId int, CustName varchar(100))
GO
INSERT INTO tbl2 VALUES (1 ,'N1')
GO

For the above tables, if you run

 SELECT a.CustID FROM tbl1 AS a 
  WHERE EXISTS (SELECT b.CustID FROM tbl2 b WHERE (a.CustID=b.CustID))

You will get 2 records.

And if you run

   SELECT a.CustID FROM tbl1 AS a
  INTERSECT
  SELECT b.CustID FROM tbl2 AS b

You will get 1 record.

Note : If you use DISTINCT with the query 1, both will result in same output.

  SELECT DISTINCT a.CustID FROM tbl1 AS a 
  WHERE EXISTS (SELECT b.CustID FROM tbl2 b WHERE (a.CustID=b.CustID))
like image 82
PSK Avatar answered Sep 25 '22 11:09

PSK