The UNION operation combines rows from different tables into a single result set, removing duplicate rows. The syntax format is: SELECT column_list FROM table1 UNION SELECT column_list FROM table2..., where table1 and table2 are the tables to be merged. The UNION operation requires that the participating tables have the same number of columns and data types, and that duplicate rows are removed.
UNION operation in SQL
What is the UNION operation?
The UNION operation combines rows from two or more tables into a single result set, thereby removing duplicate rows.
How to use UNION operation?
The syntax format of the UNION operation is:
<code class="sql">SELECT column_list FROM table1 UNION SELECT column_list FROM table2 ...</code>
Among them:
column_list
Specifies the columns to be retrieved from each table Columns table1
, table2
, ... are the tables to be mergedExample
For example, assume the students
table and the teachers
table have the following data:
students | |
---|---|
John | 20 |
Mary | 22 |
Bob | 25 |
teachers | |
---|---|
Alice | 30 |
David | 35 |
Susan | 40 |
Use the UNION operation to merge the two tables:
<code class="sql">SELECT name, age FROM students UNION SELECT name, age FROM teachers;</code>
The result will look like this:
name | age |
---|---|
John | 20 |
Mary | 22 |
Bob | 25 |
30 | |
35 | |
40 |
Tables participating in the UNION operation must have the same number of columns and data types.
ORDER BY
.
The above is the detailed content of How to use union in sql. For more information, please follow other related articles on the PHP Chinese website!