The UNION operator combines the result sets of two or more SELECT statements and returns distinct rows (duplicates removed). Use UNION ALL when you want to keep duplicates.
UNION removes duplicate rows by default.ORDER BY once at the end to sort the combined results.UNION removes duplicates; UNION ALL retains them.
-- Basic UNION syntax:
combine two SELECT results into one distinct result set
SELECT columns
FROM table1
UNION
SELECT columns
FROM table2;
-- Example: get all unique product names from two product tables
SELECT product_name FROM products_electronics
UNION
SELECT product_name FROM products_furniture;
-- Example: unique customer names from north and south regions
SELECT customer_name FROM customers_north
UNION
SELECT customer_name FROM customers_south;
-- Example: retain duplicates using UNION ALL
SELECT city FROM region_a
UNION ALL
SELECT city FROM region_b;
When the server executes a UNION, it runs each SELECT, concatenates the results, and then performs a distinct operation (de-duplication). This can have performance implications for large result sets; UNION ALL is faster when de-duplication is not needed.
Important: column order and compatible data types matter — mismatched numbers or incompatible types will cause errors.
UNION ALL when you don't need to remove duplicates — it's more efficient.ORDER BY once at the end to sort the final combined result.UNION, then change to UNION ALL and observe differences.ORDER BY at the end.