How To Use Union In Sql in SQL
How to Use UNION in SQL
The UNION operator is used to combine the result sets of two or more SELECT statements into a single result set. It removes duplicate rows by default.
Syntax:
SELECT column1, column2, ...FROM table1UNIONSELECT column1, column2, ...FROM table2;Key Points:
Each
SELECTmust have the same number of columns.Corresponding columns must have compatible data types.
By default,
UNIONremoves duplicates (likeDISTINCT).To include duplicates, use
UNION ALL.
Example:
Suppose you have two tables: customers_2023 and customers_2024. To get a combined list of all customers:
SELECT customer_id, customer_nameFROM customers_2023UNIONSELECT customer_id, customer_nameFROM customers_2024;Example with UNION ALL (includes duplicates):
SELECT customer_id, customer_nameFROM customers_2023UNION ALLSELECT customer_id, customer_nameFROM customers_2024;Notes:
The order of columns matters.
You can add
ORDER BYat the very end to sort the combined results.
If you want, I can help with examples tailored to your data!