Introduction
In this tutorial, I am going to explain working with MySQL UNION operator with examples. Without wasting time, let’s start.
UNION In MySQL
UNION is used for combining two or more separate commands to return a single output. The the union operator is used to combine the result set of two or more SELECT statements. UNION is useful because we have some information in multiple tables, and we want to fetch rows from all of them at once. We want to select several sets of rows from the same table, but some conditions that characterize each set are not easy to write as a single WHERE clause. UNION allows retrieval of each set with a simpler WHERE clause in its own SELECT statement. The rows retrieved by each are combined and produced as the final command result. The unions are useful if you wish to join the results from more than one query, but be aware that the number of the returned columns by each select query should be the same.
Syntax
SELECT column1, column2, ...
FROM table_name1
UNION [ALL | DISTINCT]
SELECT column1, column2, ...
FROM table_name2
[UNION [ALL | DISTINCT]
SELECT column1, column2, ...
FROM table_name3
...];
Example
SELECT id,name FROM my_table
UNION
SELECT id,name FROM my_table;
Without wasting time, let’s see the example
CREATE DATABASE UNION_OPERATORS;
USE UNION_OPERATORS;
/ Create tables /
CREATE TABLE U1 (
U_id INT NOT NULL
);
CREATE TABLE U2 (
U_id INT NOT NULL
);
/ Insert some values into them /
INSERT INTO U1 VALUES (101), (201), (301);
INSERT INTO U2 VALUES (51), (201), (301);
/ Now, retrieve the result from the SELECT query /
SELECT U_id
FROM U1
UNION
SELECT U_id
FROM U2;

Now, try to understand the concept of UNION with a Venn diagram.

UNION ALL
The UNION ALL operator selects all rows from each table and combines it into a single table. The UNION and UNION ALL are different in that UNION ALL will not drop duplicate rows and UNION eliminates duplicate rows. It just pulls all rows from all tables fitting our command specifics and combines them into a table.







Join the conversation! Your thoughts help the community grow.