SQL JOIN's revisited.

Yesterday I was asked what's the difference between UNION and UNION ALL, it made me think, I've been writing Stored Procedures for SQL Server for quite some time now. But almost always forget what what the difference between the two. It's time to reinforce it by writing it down through this blog.


UNION is used to combine result-sets of two or more SELECT statements,  the difference is really simple in UNION it only joins distinct values, meaning if there are duplicates it wont show it from the result-set, that's where ALL keyword is used when you want to include the duplicates in return.

Union Syntax:

SELECT ProductId
FROM Products
UNION
SELECT  ProductId
FROM Orders

This will return unique ProductId from Products and Orders Table combined and will ignore duplicates.

Up Next differences between INNER JOIN, OUTER JOIN, LEFT and RIGHT JOIN and let's not forget CROSS JOIN

CROSS JOIN
Using cross join multiplies your rows from the first table to the rows of the second table, which produces a Cartesian product

INNER JOIN
Also known as the default join, simply joins both table as long as there's a match between two tables rows.

LEFT JOIN
Returns all rows in the left table with matching rows on the right table, it return null on the rows with no matching values from the right table.

SELECT p.ProductId, p.ProductName, o.Qty
FROM Products p
LEFT JOIN Orders o ON p.ProductId = o.ProductId

Here Products (Left table) that are not in Orders(Right table) will simply have a null value.

RIGHT JOIN
simply the opposite or Left Join,  need I say more?

Let's include the Having keyword its usually used to with grouping result-set and Having adds a condition to the grouping. without the Group By clause it acts similar to a WHERE clause.

Comments

Popular posts from this blog

Serializing JSON string to ExpandoObject

XML to ExpandoObject using Recursion in C#

Automatically Discover and Assign Parameter with Values to a Stored Procedure Call in C#