Summary: In this chapter, we will learn how to use MySQL UNION operator to combine two or more result sets from multiple SELECT statements into a single result set.
Introducing to MySQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.
The syntax of the MySQL UNION is as follows:
1
2
3
| SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; |
NOTE: UNION operator eliminates duplicate rows from the result. while UNION ALL returns duplicate rows also mean result will be same.
MySQL UNION example
Let’s practice with an example of using MySQL UNION to get a better understanding.
First we will create quickly one customers table, In details we will learn later and we have employees table already in our Sample Database.
Suppose we want to combine data from the customers and employees tables into a single result set, we can UNION operator as the following query:
1
2
3
| SELECT CustomerId, CustomerName FROM customers UNION SELECT employeeid, firstname FROM employees |
Here is the output:
In this chapter, we have learnt how to use MySQL UNION statement to combine data from multiple tables into a single result set.
MySQL ORDER BY MySQL ALIAS
MySQL ORDER BY MySQL ALIAS