Home >Database >SQL >The role of union in sql

The role of union in sql

下次还敢
下次还敢Original
2024-05-02 00:00:26818browse

The UNION operator combines rows from multiple tables with the same column structure into a single result set, eliminating duplicate rows and automatically converting data types. 1. Merge rows from different tables; 2. Eliminate duplicate rows; 3. Convert data types to match column structure.

The role of union in sql

The role of UNION in SQL

The UNION operator is used to merge data from two or more tables with Rows with the same column structure form a new result set.

Usage:

The syntax of UNION is as follows:

<code>SELECT 列名1, 列名2, ...
FROM 表名1
UNION
SELECT 列名1, 列名2, ...
FROM 表名2</code>

Function:

  • Merge rows: Merge rows from multiple tables together to form a new result set.
  • Eliminate duplicate rows: By default, UNION will eliminate duplicate rows.
  • Different tables: Rows from different tables can be merged as long as they have the same column structure.
  • Data type conversion: UNION will automatically convert columns of different data types into compatible data types.

Notes:

  • Column order and data type:The columns of the merged table must be in the same order and Data type arrangement.
  • NULL values: UNION treats NULL values ​​as matching values ​​even if they appear in different columns in different rows.
  • ALL and DISTINCT: UNION can use ALL or DISTINCT keywords, ALL contains all rows and DISTINCT returns only unique rows.

Example:

Merge rows from two tables containing country information:

<code>SELECT Country, Population
FROM Countries
UNION
SELECT Country, Population
FROM World_Nations;</code>

Result:

The merged table will contain data for all countries with no duplicate rows.

The above is the detailed content of The role of union in sql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:How to use modify in sqlNext article:How to use modify in sql