MariaDB UNION Operator
In MariaDB database, UNION Operator is used to combine the result sets of two or more SELECT statements. It removes duplicate rows between the various SELECT statements.
SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions] UNION [DISTINCT] SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions];
# Note: Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.
# Return Single Field using UNION Operator
Let's take an example of MariaDB UNION Operator that returns one field from multiple SELECT statements. (Both tables having a same common field).
We have two tables "Student" and "Students".
SELECT student_name FROM Student UNION SELECT student_name FROM Students;
It shows the student_name from both table where duplicates names are removed.
# UNION Operator with ORDER BY Clause
Use UNION operator with ORDER BY clause to retrieve multiple columns from both table.
SELECT student_id, student_name FROM Students WHERE student_name = 'Komal' UNION SELECT student_id, salary FROM Student WHERE student_id > 4 ORDER BY 1;