Union Usage of SQL

Source: Internet
Author: User

The Union in SQL is very common, especially when creating views, which are completely inseparable from union.

The SQL union operation conforms to and results from two or more SELECT statements, and each SELECT statement inside the Union must have the same number of columns. The column must also have a similar data type. Also, the order of the columns in each SELECT statement must be the same.

The union consists of the Union and Union all two syntaxes, as follows:

SQL UNION Syntax
SELECT  from table1 UNION SELECT  from Table2;
SQL UNION All syntax
SELECT  from table1 UNION  All SELECT  from Table2;

The difference between the two is that the union all includes duplicate data.

Having finished the grammar, let's take a simple example.

First, the table structure, very simple, two tables

Teacher

Student.

As you can see, the table structure of the two tables is the same.

The union query for First_Name is now in progress.

Select  from Union Select  from student;

The query results are as follows:

You can see data that is not duplicated.

After the union all is changed.

Select  from Union  All Select  from student;

The query results are as follows:

As you can see, the data is duplicated.

But what if we also query first_name and last_name?

Select  from Union Select   from student;

The results are as follows:

After you change to union ALL

Select  from Union  All Select   from student;

Query Result:

As you can see, the result is the same, because First_Name and last_name are judged together, there is no duplication of data.

Reference:

Http://www.w3cschool.cc/sql/sql-union.html

Union Usage of SQL

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.