Homes and Property Knowledge by Homes.pk
SQL UNION ALL Tutorial: Merging Data from Multiple Queries
  • April 10, 2025 4:57 am
  • Toronto, Canada

In this SQL tutorial, you’ll learn how to use the UNION ALL operator to combine the results of multiple SQL queries. Unlike the regular UNION operator, UNION ALL returns all rows, including duplicates, from the SELECT queries. This makes it an ideal choice for scenarios where you need to preserve all data, regardless of duplication. We’ll walk through basic usage, syntax, and real-world examples to help you understand how to effectively apply UNION ALL to merge data from different tables or queries. Additionally, we’ll compare it with UNION and explore performance considerations.

SQL Statment
use ContosoRetailDW
select productkey, sum(dbo.FactOnlineSales.SalesQuantity*dbo.FactOnlineSales.UnitPrice) as SalesAmount,’Online’ as Salestype
from dbo.FactOnlineSales
group by ProductKey
union all
select dbo.FactSales.ProductKey,sum(dbo.FactSales.SalesQuantity*dbo.FactSales.unitprice) SalesAmount,’Store’ as SalesType
from dbo.FactSales
group by dbo.FactSales.ProductKey

use ContosoRetailDW
select sum(dbo.FactOnlineSales.SalesAmount) as SalesAmount,’Online’ as Salestype
from dbo.FactOnlineSales

union all
select sum(dbo.FactSales.SalesAmount) SalesAmount,’Store’ as SalesType
from dbo.FactSales

Location

Toronto,Canada

Leave a Review

Your email address will not be published. Required fields are marked *