The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:
Note: The column names in the result-set are usually equal to the column names in the first SELECT statement.
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
And a selection from the "Suppliers" table:
The following SQL statement returns the cities (only distinct values) from both the "Customers" and the "Suppliers" table:
Note: If some customers or suppliers have the same city, each city will only be listed once, because UNION selects only distinct values. Use UNION ALL to also select duplicate values!
The following SQL statement returns the cities (duplicate values also) from both the "Customers" and the "Suppliers" table:
The following SQL statement returns the German cities (only distinct values) from both the "Customers" and the "Suppliers" table:
The following SQL statement returns the German cities (duplicate values also) from both the "Customers" and the "Suppliers" table:
The following SQL statement lists all customers and suppliers:
Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table or a column a temporary name. An alias only exists for the duration of the query. So, here we have created a temporary column named "Type", that list whether the contact person is a "Customer" or a "Supplier".