Friday 1 September 2017

Difference between Inner Join and Left Semi Join

Semi joins will not have any syntax in SQL.
The following are the logical join operators that SQL Server supports:
  • Inner join
  • Outer join
  • Cross join
  • Cross apply
  • Semi-join
  • Anti-semi-join

An INNER JOIN returns the columns from both tables. A LEFT SEMI JOIN only returns the records from the left-hand table. It's equivalent to (in standard SQL):

SELECT name 
FROM table_1 a 
WHERE EXISTS(
SELECT * FROM table_2 b WHERE (a.name=b.name))

If there are multiple matching rows in the column of right-side table, an INNER JOIN will return one row for each matching column, while a LEFT SEMI JOIN only returns the matching rows from the left table. That's why you're seeing a different number of rows in your result.

Example:

Suppose there are 2 tables TableA and TableB with only 2 columns (Id, Data) and following data:

TableA:
Id Data
1 DataA11
1 DataA12
1 DataA13
2 DataA21
3 DataA31

TableB:
Id Data
1 DataB11
2 DataB21
2 DataB22
2 DataB23
4 DataB41

Inner Join on column Id will return columns from both the tables and only the matching records:
Id Data Id Data
1 DataA11  1 DataB11
1 DataA12  1 DataB11
1 DataA13  1 DataB11
2 DataA21  2 DataB21
2 DataA21  2 DataB22
2 DataA21  2 DataB23

Left Join (or Left outer join) on column Id will return columns from both the tables and matching records with records from left table (Null values from right table):
Id Data Id Data
1 DataA11  1 DataB11
1 DataA12  1 DataB11
1 DataA13  1 DataB11
2 DataA21  2 DataB21
2 DataA21  2 DataB22
2 DataA21  2 DataB23
3 DataA31

Right Join (or Right outer join) on column Id will return columns from both the tables and matching records with records from right table (Null values from left table):
Id Data Id Data
1 DataA11 1 DataB11
1 DataA12 1 DataB11
1 DataA13 1 DataB11
2 DataA21 2 DataB21
2 DataA21 2 DataB22
2 DataA21 2 DataB23
4 DataB41
    
Outer Join (or Full outer join) on column Id will return columns from both the tables and matching records with records from left table (Null values from right table) and records from right table (Null values from left table):
Id Data Id Data
1 DataA11 1 DataB11
1 DataA12 1 DataB11
1 DataA13 1 DataB11
2 DataA21 2 DataB21
2 DataA21 2 DataB22
2 DataA21 2 DataB23
3 DataA31
4 DataB41
    
Left Semi Join on column Id will return columns only from left table and matching records only from left table:
Id Data
1 DataA11
1 DataA12
1 DataA13
2 DataA21

Please refer the below link for other types of semi joins.
https://blog.jooq.org/2015/10/13/semi-join-and-anti-join-should-have-its-own-syntax-in-sql/
https://blogs.msdn.microsoft.com/craigfr/2006/07/19/introduction-to-joins/
https://technet.microsoft.com/en-us/library/ms191255(v=sql.105).aspx

No comments:

Post a Comment

GROUPBY VS PARTITIONBY