First day of SQL Study -- Understanding of SQL UNION and UNION ALL operators

Source: Internet
Author: User

SQL UNION operator
The UNION operator is used to merge the result sets of two or more SELECT statements.
Note::
1. SELECT statements within UNION must have the same number of columns. Columns must also have similar data types. In addition, the columns in each SELECT statement must be in the same order.
2. The column name in the UNION result set is always the same as the column name in the first SELECT statement in the UNION.
SQL UNION syntax (no duplicate values in the result set ): Copy codeThe Code is as follows: SELECT s FROM table1
UNION
SELECT s FROM table2

SQL UNION ALL syntax (the result set has repeated values ):Copy codeThe Code is as follows: SELECT s FROM table1
UNION ALL
SELECT s FROM table2

Example Table:
Table 1 (Employees_China ):
E_ID E_Name
01 Zhang, Hua
02 Wang, Wei
03 Carter, Thomas
04 Yang, Ming
Table 2 (Employees_USA ):
E_ID E_Name
01 Adams, John
02 Bush, George
03 Carter, Thomas
04 Gates, Bill
Instance:
About UNION:Copy codeThe Code is as follows:
SELECT E_Name FROM Employees_China
UNION
SELECT E_Name FROM Employees_USA

The result is as follows (removing duplicate data ):

E_Name
Zhang, Hua
Wang, Wei
Carter, Thomas
Yang, Ming
Adams, John
Bush, George
Gates, Bill

About union all:Copy codeThe Code is as follows: SELECT E_Name FROM Employees_China
UNION ALL

SELECT E_Name FROM Employees_USA

The result is as follows (repeated data is retained ):

E_Name
Zhang, Hua
Wang, Wei
Carter, Thomas
Yang, Ming
Adams, John
Bush, George
Carter, Thomas
Gates, Bill

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.