MySQL Tutorial
The UNION operator is used to combine the results of two or more SELECT queries into a single result set.
These are basic rules for combining the result sets of two SELECT queries by using UNION:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Let's put these statements into real use.
We've a table named Students and Teachers in our database that contains the following records:
ROLL_NO | NAME | SUBJECT |
---|---|---|
1 | Will | C++ |
2 | SAM | Python |
3 | Rani | Node.js | 4 | Rim | Java |
5 | Micheal | JAVA |
6 | Lara | PHP |
TECH_NO | NAME | SUBJECT | ROLL_NO |
---|---|---|---|
20 | Kayla | PHP | 6 |
21 | Albert | Java | 2 |
21 | Albert | Java | 5 |
22 | Helen | Node.js | 3 | 23 | Anne | Python | 2 |
24 | Jaime | C++ | 1 |
The following MySQL statement returns the SUBJECTS (only distinct values) from both the "Students" and the "Teachers" table:
SELECT SUBJECT FROM Students
UNION
SELECT SUBJECT FROM Teachers
ORDER BY SUBJECT;
Now, after executing the above MySQL statement,
SUBJECT |
---|
C++ |
Java |
Node.js |
PHP | Python |
If some Students or teachers have the same SUBJECT, each SUBJECT will only be listed once, because UNION selects only distinct values.
Use UNION ALL to also select duplicate values!
The following MySQL statement returns the SUBJECTS (all values) from both the "Students" and the "Teachers" table:
SELECT SUBJECT FROM Students
UNION ALL
SELECT SUBJECT FROM Teachers
ORDER BY SUBJECT;
Now, after executing the above MySQL statement,
SUBJECT |
---|
C++ |
C++ |
Java |
Java |
Java |
Java |
Node.js |
Node.js |
PHP |
PHP | Python | Python |