16. MySQL: UNION Operator

16. MySQL: UNION Operator

The UNION operator in MySQL is used to combine the results of two or more SELECT statements into a single result set.

It is a useful tool for merging data from multiple tables or for combining data that is stored in different formats or structures.

Points To Remember:

  1. The number of columns selected in each SELECT statement must be the same.

  2. The columns selected in each SELECT statement must have the same data type and be in the same order.

  3. If you want to include duplicate rows in the result set, use UNION ALL instead of UNION.

  4. Be mindful of the performance of your query when using UNION, as it can slow down query performance.

  5. When using UNION, if the SELECT statements have different WHERE clauses, it's important to consider the join conditions, indexes, and other factors that could affect query performance.

  6. Use aliases for the column names in the final result set for better readability.


UNION OPERATOR:

The UNION operator eliminates duplicate rows from the final result set.

Syntax:

SELECT column_1, column_2, ... 
FROM table_1
UNION
SELECT column_1, column_2, ... 
FROM table_2

Let us have all the first names and last names from the actor and staff table and check how many results we get.

SELECT first_name, last_name FROM actor
UNION
SELECT first_name, last_name FROM staff;

Output:


UNION ALL:

UNION ALL operator includes all duplicate rows in the result set.

Syntax:

SELECT column_1, column_2, ... 
FROM table_1
UNION ALL
SELECT column_1, column_2, ... 
FROM table_2

Let us again have all the first names and last names from the actor and staff table and check how many results we get.

SELECT first_name, last_name FROM actor
UNION ALL
SELECT first_name, last_name FROM staff;

Output:


So we have 206 rows returned for the UNION operator and we have 211 rows returned for the UNION ALL Operator.

Thus we know we had 5 duplicate values in the table.


In summary, the UNION operator in MySQL is used to combine the results of two or more SELECT statements into a single result set. It eliminates duplicate rows from the final result set and is useful for merging data from multiple tables or for combining data that is stored in different formats or structures.


'll meet again tomorrow!

To see more examples, you can always refer w3 schools; it has always been my go-to website to understand things.

References: w3schools.com/mysql/default.asp

*****All the outputs provided are a snippet of the actual result.