πŸ“ What You’ll Learn

  • What UNION does
  • Syntax and structure
  • Examples of using UNION
  • Difference between UNION and UNION 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