Skip to the content.

MySQL UNION

What is a Union?

Unions combine the results from multiple SELECT queries into a consolidated result set. Suppose we have two tables as follows



Let’s now create a UNION query to combines both tables using DISTINCT

SELECT column1, column2 FROM `table1`
UNION DISTINCT
SELECT  column1,column2  FROM `table2`;

NOTE: MySQL uses the DISTINCT clause as default when executing UNION queries if nothing is specified.

Let’s now create a UNION query to combines both tables using ALL

SELECT `column1`,` column2` FROM `table1`
UNION ALL
SELECT ` column1`,` column2`  FROM `table2`;


Why use Unions?

Suppose there is a flaw in your database design and you are using two different tables meant for the same purpose. You want to consolidate these two tables into one while omitting any duplicate records from creeping into the new table. You can use UNION in such cases.

Summary

Ref: For more informations and examples follow the link: https://www.guru99.com/unions.html