MySQL UNION Syntax

UNION is used to combine the result from multiple SELECT statements into a single result set.

The column names from the first SELECT statement are used as the column names for the results returned. Selected columns listed in corresponding positions of each SELECT statement should have the same data type. (For example, the first column selected by the first statement should have the same type as the first column selected by the other statements.)

The union syntax is as follows.

SELECT statement
UNION [DISTINCT | ALL] SELECT statement

By default the MySQL UNION removes all duplicate rows from the result set even if you don’t explicit using DISTINCT after the keyword UNION.

If you use UNION ALL explicitly, the duplicate rows remain in the result set. You only use this in the cases that you want to keep duplicate rows or you are sure that there are no duplicate rows in the result set.

Example:

(SELECT ssn, fname FROM employee)
UNION
(SELECT sid, first_name FROM student);

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.