Updated on 2025-09-05 GMT+08:00

Union/Union ALL

Function

  • UNION/UNION DISTINCT returns the union of multiple query results and removes duplicate rows.
  • UNION ALL returns the union set of multiple query results, including duplicate rows.

Syntax Format

1
2
3
4
5
SELECT_statement_1
UNION [ALL | DISTINCT]
SELECT_statement_2
[UNION [ALL | DISTINCT]
SELECT_statement_3 ...]

Precautions

  • UNION joins tables based on certain conditions. The number of columns returned by each SELECT statement must be the same, and the column types must be the same. The column names can be different. The column names of the first query are used as the column names of the result set.
  • The union query can be used only in subqueries.

Example

Output distinct records found in Orders1 and Orders2 tables.
1
2
3
4
SELECT * FROM (
  SELECT  * FROM Orders1
    UNION SELECT  * FROM Orders2
);