SELECT columns FROM table1
UNION[ALL]SELECT columns FROM table2;
Example
SELECT first_name, email,'customer'AS source
FROM customers
UNIONALLSELECT first_name, email,'employee'AS source
FROM employees;
Output
-- Combined list of customers and employees
Note UNION removes duplicates (slower, requires sorting). UNION ALL keeps all rows (faster). Use UNION ALL unless you specifically need deduplication. Both queries must have the same number of columns with compatible types.
Frequently asked questions
How does Python handle union?
This task is covered in 2 stacks on this page: Python, SQL. The "typing Module Essentials" snippet in Python uses `from typing import Optional, Union, TypeVar, Generic`.
Which code does the Python example use?
The "typing Module Essentials" snippet uses `from typing import Optional, Union, TypeVar, Generic`, from the Common Standard Library section of the Python cheat sheet.
Which stacks cover "union" on this page?
Python, SQL. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "typing Module Essentials": Since 3.10, use X | Y instead of Union[X, Y]. Since 3.12, use the type parameter syntax: class Stack[T]: instead of TypeVar + Generic.