SQL UNION Operator

« Previous Chapter Next Chapter »

The SQL UNION operator combines two or more SELECT statements.

The SQL UNION Operator

The UNION operator is used to combine the result-set of two or more SELECT statements.

Note: each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

SQL UNION Syntax

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.

SQL UNION ALL Syntax

SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2

PS: The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.

SQL UNION Example

Look at the following tables:

"Friends_Australia":

E_ID E_Name
01 Karmen, Kasa
02 Jacob, Mary
03 Jacob, Saurav
04 Maxwell, Glen

"Friends_USA":

E_ID E_Name
01 Turner, Sally
02 Kent, Clark
03 Jacob, Saurav
04 Scott, Saurav

Now we want to list all the different Friends in Australia and USA.

We use the following SELECT statement:

SELECT E_Name FROM Friends_Australia
UNION
SELECT E_Name FROM Friends_USA

The result-set will look like this:

E_Name
Karmen, Kasa
Jacob, Mary
Jacob, Saurav
Maxwell, Glen
Turner, Sally
Kent, Clark
Scott, Saurav

Note: This command cannot be used to list all Friends in Australia and USA. In the example above we have two Friends with equal names, and only one of them will be listed. The UNION command selects only distinct values.

SQL UNION ALL Example

Now we want to list all Friends in Australia and USA:

SELECT E_Name FROM Friends_Australia
UNION ALL
SELECT E_Name FROM Friends_USA

Result

E_Name
Karmen, Kasa
Jacob, Mary
Jacob, Saurav
Maxwell, Glen
Turner, Sally
Kent, Clark
Jacob, Saurav
Scott, Saurav

« Previous Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!