SQL UNION operator

Here is a clear, practical guide to the SQL UNION operator, with examples, rules, and best-practice notes.


βœ… What UNION Does

UNION combines the result sets of two or more SELECT statements into a single result set.

  • Duplicates are removed (like SELECT DISTINCT).

  • Columns must be compatible (same number of columns and compatible data types).


πŸ”Ή Basic Syntax

SELECT column1, column2, ...
FROM table1

UNION

SELECT column1, column2, ...
FROM table2;


πŸ”Ή Example: Combine data from two tables

SELECT name, email FROM customers
UNION
SELECT name, email FROM prospects;

βœ” Removes duplicate rows
βœ” Returns one combined result set


πŸ”₯ UNION ALL (keeps duplicates)

UNION ALL is faster because it does NOT check for duplicates.

SELECT name FROM employees_2023
UNION ALL
SELECT name FROM employees_2024;

Use when:

  • You want all rows, including duplicates

  • You want better performance on large datasets


🧠 Important Rules

  1. Each SELECT must have the same number of columns

  2. Columns must be in the same order

  3. Columns must be compatible types (e.g., INT with BIGINT, VARCHAR with TEXT)

  4. ORDER BY applies once at the end:

SELECT name FROM table_a
UNION
SELECT name FROM table_b
ORDER BY name;

πŸ”₯ Practical Examples

1. Combine active and archived orders

SELECT id, total, created_at FROM orders
UNION ALL
SELECT id, total, created_at FROM archived_orders;

2. Get a list of unique cities from multiple tables

SELECT city FROM customers
UNION
SELECT city FROM suppliers;

3. Find all unique tags across two tag tables

SELECT tag FROM post_tags
UNION
SELECT tag FROM product_tags;

πŸ”§ Using UNION inside subqueries

SELECT *
FROM (
SELECT user_id FROM orders
UNION
SELECT user_id FROM logins
) AS all_users
ORDER BY user_id;

🏎 Performance Tips

βœ” Use UNION ALL when duplicates don’t matterβ€”much faster
βœ” Apply ORDER BY only at the end
βœ” Ensure SELECTs are using indexed columns when possible
βœ” Avoid mixing very different data types

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

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