UNION
Function
UNION returns the union of the results of multiple queries. UNION removes duplicate rows by default, while UNION ALL retains duplicate rows.
Syntax
select_statement UNION [ ALL ] select_statement;
Parameters
| Parameter | Description |
|---|---|
| UNION | Set union operation. Merges the results of multiple queries. Removes duplicate rows by default. |
| ALL | When the ALL keyword is added, duplicate rows are retained (i.e., no deduplication). The performance of UNION ALL is typically better than UNION because no deduplication operation is required. |
Precautions
- Each SELECT statement must return the same number of columns.
- The data types of corresponding columns must be compatible.
- The column names of the result set are determined by the first SELECT statement.
- UNION removes duplicates by default. UNION ALL does not. In scenarios where deduplication is not required, you are advised to use UNION ALL for better performance.
- Parentheses can be used to control the precedence of multiple set operations (UNION, INTERSECT, EXCEPT) (Spark 4.0).
Examples
UNION with deduplication:
SELECT * FROM student_1 UNION SELECT * FROM student_2;
UNION ALL without deduplication:
SELECT * FROM student_1 UNION ALL SELECT * FROM student_2;
Using parentheses to control precedence (Spark 4.0):
(SELECT * FROM student_1 UNION ALL SELECT * FROM student_2) INTERSECT SELECT * FROM student_3;
Multi-table UNION:
SELECT name FROM student_1 UNION ALL SELECT name FROM student_2 UNION ALL SELECT name FROM student_3;
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot