π What Youβll Learn
- What
UNION
does - Syntax and structure
- Examples of using
UNION
- Difference between
UNION
andUNION ALL
π What Is UNION?
The UNION
operator in SQL is used to combine the result sets of two or more SELECT queries into a single result set.
- It eliminates duplicate rows by default.
Itβs useful when you need to combine data from similar tables or queries with the same structure.
π§± UNION Syntax
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
π§ͺ Example: Combine Customers from Two Regions
SELECT name, region
FROM customers_east
UNION
SELECT name, region
FROM customers_west;
This query combines the customers from the East and West regions into a single list, excluding duplicates.
π§ͺ Example: Combine Products and Services
SELECT product_name AS item_name
FROM products
UNION
SELECT service_name AS item_name
FROM services;
Here, weβre combining products and services into one column, showing all unique items.
βοΈ UNION vs UNION ALL
Feature | UNION | UNION ALL |
---|---|---|
Duplicates | β Removes duplicates | β Does not remove |
Performance | β³ Slightly slower | π Faster |
Use Case | When you need unique results | When you want all results |
π Recap
UNION
combines results from multiple queries into a single result set- Removes duplicate rows by default
UNION ALL
includes all rows, even duplicates