Home > Database > SQL > How to use union in sql

How to use union in sql

下次还敢
Release: 2024-05-02 04:18:17
Original
969 people have browsed it

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.

How to use union in sql

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>
Copy after login

Among them:

  • column_list Specifies the columns to be retrieved from each table Columns
  • table1, table2, ... are the tables to be merged

Example

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>
Copy after login

The result will look like this:

##Alice30David35Susan40
name age
John 20
Mary 22
Bob 25
##Notes

Tables participating in the UNION operation must have the same number of columns and data types.
  • UNION operation does not retain duplicate rows. The
  • UNION operation can be combined with other SQL operations, such as
  • WHERE
  • and 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template