![]() |
VOOZH | about |
The UNION operator in MySQL combines the results of multiple SELECT statements into a single result set. It ensures consistent structure by requiring the same number of columns with compatible data types.
Syntax:
SELECT column1, column2, ...
FROM table1
WHERE condition
UNION
SELECT column1, column2, ...
FROM table2
WHERE condition;Note: UNION removes duplicate records by default.
Letβs explore how the MySQL UNION operator works using examples. These examples demonstrate how to combine results from multiple tables. First, letβs create two tables on which the UNION operator will be applied:
This example shows how to merge names from two tables into a single result. It also adds a label to identify the source of each record.
Query:
SELECT name, 'Student' AS type
FROM students
UNION
SELECT name, 'Teacher' AS type
FROM teachers;Output:
This example demonstrates combining filtered data from both tables. It helps retrieve only relevant records based on conditions.
Query:
SELECT name, 'Student' AS type
FROM students
WHERE age > 15
UNION
SELECT name, 'Teacher' AS type
FROM teachers
WHERE years_of_experience > 8;Output: