Get the App
SLTechnology News&Howtos  ›  Database  › 

SQL Union and SQL Union All usage

Shulou Source: shulou.com Published: 2022-06-01 18:39:59 10月03日 Update

SQL Union usage

SQL Union and SQL Union All usage

SQL UNION operator

The UNION operator is used to merge the result sets of two or more SELECT statements.

Note that SELECT statements within UNION must have the same number of columns. Columns must also have similar data types. At the same time, the columns in each SELECT statement must be in the same order.

SQL UNION syntax SELECT column_name (s) FROM table_name1UNIONSELECT column_name (s) FROM table_name2

Note: by default, the UNION operator chooses a different value, that is, UNION is de-duplicated. If duplicate values are allowed, use UNION ALL.

SQL UNION ALL syntax SELECT column_name (s) FROM table_name1UNION ALLSELECT column_name (s) FROM table_name2

In addition, the column name in the UNION result set is always equal to the column name in the first SELECT statement in UNION.

The purpose of the UNION directive is to merge the results of two SQL statements. From this point of view, UNION is somewhat similar to JOIN because both instructions can retrieve data from multiple tables. Union just joins two results together to display, not join two tables. The syntax of UNION is as follows:

And we need to find out all the days when there is a sales. To do this, we use the following SQL statement: SELECT Date FROM Store_InformationUNIONSELECT Date FROM Internet_Sales result:

It is worth noting that if we use "SELECT DISTINCT Date" in any SQL statement (or both), we will get exactly the same result.

Tags: Statement result two operator syntax same multiple instruction purpose join different similar just at the same time data quantity date comment for type Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Redmi Shulou Information Huawei Shulou Technology