JOIN combines related columns horizontally across tables, while UNION combines compatible result sets vertically. They can be used together in complex SQL queries.
Real-world reporting sometimes requires combining data from multiple relationships and then combining separate result sets.
Create a combined customer activity report from different transaction sources after joining each source with customer information.
SELECT
c.CustomerName,
o.OrderID AS ActivityID
FROM Customers c
INNER JOIN Orders o
ON c.CustomerID = o.CustomerID
UNION
SELECT
c.CustomerName,
r.ReturnID AS ActivityID
FROM Customers c
INNER JOIN Returns r
ON c.CustomerID = r.CustomerID;
Useful in consolidated reporting, system integration, transaction analysis, and multi-source data preparation.
- JOIN combines related tables horizontally.
- UNION combines result sets vertically.
- UNION requires compatible column structures.
- JOIN and UNION can be used in the same query.
- Complex reports may require both techniques.
Can JOIN and UNION be used together?
Yes. JOIN can combine related data within each query, while UNION can combine the resulting datasets.
What is the main difference between JOIN and UNION?
JOIN combines columns from related rows, while UNION combines rows from compatible result sets.