MySQL Tutorial
The UNION operator in MySQL is used to combine results from multiple SELECT queries into a single result set.
SELECT statements.SELECT column1, column2 FROM table1 UNION SELECT column1, column2 FROM table2;
If you want to keep duplicate records, use UNION ALL:
SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2;
Note
The column names in the result-set are usually equal to the column names in the first SELECT statement.
We have two tables:
|
student_id |
name |
course |
score |
|---|---|---|---|
|
1 |
Alice |
Math |
85 |
|
2 |
Bob |
Science |
70 |
|
student_id |
name |
course |
score |
|---|---|---|---|
|
3 |
Charlie |
Math |
90 |
|
4 |
David |
English |
60 |
The following SQL statement Combining Students from Two Branches(without duplicates)
Try it yourself
|
student_id |
name |
course |
|---|---|---|
|
1 |
Alice |
Math |
|
2 |
Bob |
Science |
|
3 |
Charlie |
Math |
|
4 |
David |
English |
The following SQL statement Combining Students from Two Branches(with duplicates)
Try it yourself
|
course |
|---|
|
Math |
|
Science |
|
Math |
|
English |
UNION ALLdoes not remove duplicates.The following SQL statement combine students with score above 80 from both tables.
Try it yourself
|
student_id |
name |
course |
score |
|---|---|---|---|
|
1 |
Alice |
Math |
85 |
|
1 |
Charlie |
Math |
90 |
UNION, removing duplicates.UNION removes duplicates automatically.UNION ALL if duplicates should be retained.WHERE conditions.