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
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.
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.
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.
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 .
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With