Interview Questions and Answers
What is the difference between INTERSECT and INNER JOIN
What is the difference between INTERSECT and INNER JOIN
1. INTERSECT filters duplicates and returns only DISTINCT rows that are common between the LEFT and Right Query, where as INNER JOIN does not filter the duplicates.To understand this difference, insert the following row into TableA
Now execute the following INTERSECT query. Notice that we get only the DISTINCT rows
Result :
Now execute the following INNER JOIN query. Notice that the duplicate rows are not filtered.
Result :
You can make the INNER JOIN behave like INTERSECT operator by using the DISTINCT operator
Result :
2. INNER JOIN treats two NULLS as two different values. So if you are joining two tables based on a nullable column and if both tables have NULLs in that joining column then, INNER JOIN will not include those rows in the result-set, where as INTERSECT treats two NULLs as a same value and it returns all matching rows.
To understand this difference, execute the following 2 insert statements
INTERSECT query
Result :
INNER JOIN query
Result :
Insert into TableA values (2, 'Mary', 'Female')
Now execute the following INTERSECT query. Notice that we get only the DISTINCT rows
Select Id, Name, Gender from TableA
Intersect
Select Id, Name, Gender from TableB
Result :
Now execute the following INNER JOIN query. Notice that the duplicate rows are not filtered.
Select TableA.Id, TableA.Name, TableA.Gender
From TableA Inner Join TableB
On TableA.Id = TableB.Id
Result :
You can make the INNER JOIN behave like INTERSECT operator by using the DISTINCT operator
Select DISTINCT TableA.Id, TableA.Name, TableA.Gender
From TableA Inner Join TableB
On TableA.Id = TableB.Id
Result :
2. INNER JOIN treats two NULLS as two different values. So if you are joining two tables based on a nullable column and if both tables have NULLs in that joining column then, INNER JOIN will not include those rows in the result-set, where as INTERSECT treats two NULLs as a same value and it returns all matching rows.
To understand this difference, execute the following 2 insert statements
Insert into TableA values(NULL, 'Pam', 'Female')
Insert into TableB values(NULL, 'Pam', 'Female')
INTERSECT query
Select Id, Name, Gender from TableA
Intersect
Select Id, Name, Gender from TableB
Result :
INNER JOIN query
Select TableA.Id, TableA.Name, TableA.Gender
From TableA Inner Join TableB
On TableA.Id = TableB.Id
Result :
Post a Comment
0 Comments