mysql
  1. mysql-union

Union - (MySQL Misc)

In MySQL, a union is used to combine the results of two or more SELECT statements into a single result set. In this tutorial, we'll discuss how to use the UNION operator in MySQL.

Syntax

The syntax for using a UNION operator in MySQL is as follows:

SELECT column1, column2, ... 
FROM table1 
UNION 
SELECT column1, column2, ... 
FROM table2;

The columns in the SELECT statement must have compatible data types between the two tables. Additionally, the number of columns in each SELECT statement must be the same.

Example

Let's say we have two tables, "employees" and "customers", both with the same structure: "id", "name", and "salary". Here's an example of how to use the UNION operator to combine the "employees" and "customers" tables:

SELECT id, name, salary 
FROM employees 
UNION 
SELECT id, name, salary 
FROM customers;

This will return a result set containing all the rows from the "employees" and "customers" tables, with duplicates removed.

Output

When we run the example code above, the output will be a result set containing the combined data from the "employees" and "customers" tables.

Explanation

In the example above, we used the UNION operator to combine the data from the "employees" and "customers" tables into a single result set. Each SELECT statement in the UNION must have the same number of columns, and the columns must be of compatible data types.

Use

Unions are useful for combining data from multiple tables into a single result set. This can be particularly useful when you have two or more tables with identical structures but different data.

Important Points

  • The number of columns in each SELECT statement must be the same.
  • The columns in each SELECT statement must be of compatible data types.
  • The order of the columns in each SELECT statement must be the same.
  • The UNION operator removes duplicates that appear in both result sets.

Summary

In this tutorial, we discussed how to use the UNION operator in MySQL to combine the results of two or more SELECT statements into a single result set. We covered the syntax, example, output, explanation, use, and important points of the UNION operator in MySQL. With this knowledge, you can now use unions to combine data from multiple tables in your MySQL database.

Published on: