Introduction to SQL Joins & Unions

16 September 2018

SQL Joins

SQL join is used to combine data from two or more tables based on a common field among them.

By using JOINs, you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how SQL should use data from one table to select the rows in another table.


SELECT a.Column1, b.Column2 FROM TableA a
INNER JOIN TableB b ON a.Id = b.AFKId

Following are the available Joins:

INNER JOIN:

This join selects the matching data from the tables based on common key.It will create the result-set by combining all rows from the tables where the value of the common field will be same.

LEFT JOIN or LEFT OUTER JOIN This join returns all the records of the table on the left side of the join and matching rows for the table on the right side of the join.If there are no any matching row on the right hand side of the oin ,result set will contain null.

RIGHT JOIN or RIGHT OUTER JOIN:

This join returns all the records of the table on the right side of the join and matching rows for the table on the left side of join.

If there are no matching row on left side of the join ,result-set will contain null values.

FULL JOIN: This Join creates the result-set by combining the result of both LEFT and RIGHT Join.The result-set will contain all the rows from both the tables. If there is no match found for any rows ,result-set will contain NULL values.

Join
Figure: Join

SQL Union

UNION combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union.


SELECT 1 AS [Column1], 2 AS [Column2]
UNION
SELECT 3 AS [Column1], 4 AS [Column2]
Union
Figure: Union

Union vs Union All

Union combines two tables by removing duplicates. Union All combines two tables by including all data even if they are duplicate .

Reference

Union vs Join

Share: Twitter Facebook Google+ LinkedIn
comments powered by Disqus