Union

The UNION keyword is used for integrating queries:

< query 1 >
UNION [ALL]
< query 2 >

The UNION clause combines the results of two SELECT statements into a single result set. If the ALL parameter is given, all the duplicates of the rows returned are retained; otherwise the result set includes only unique rows. Note that any number of queries may be combined. Moreover, the union order can be changed with parentheses.

The following conditions should be observed:

  • The number of columns of each query must be the same;
  • Result set columns of each query must be compared by the data type to each other (as they follows);
  • The result set uses the column names from the first query;
  • The ORDER BY clause is applied to the union result, so it may only be written at the end of the combined query.

Example 5.7.1

Find the model numbers and prices of the PCs and laptops:
SELECT model, price
FROM PC
UNION
SELECT model, price
FROM Laptop
ORDER BY price DESC;
mssql
🚫
[[ error ]]
[[ column ]]
[[ value ]]
modelPrice
17501200
17521150
12981050
1233980
1321970
1233950
1121850
1298700
1232600
1233600
1232400
1232350
1260350

Example 5.7.2

Find out the product type, the model number, and the price of the PCs and laptops:
SELECT Product.type, PC.model, price
FROM PC INNER JOIN
     Product ON PC.model = Product.model
UNION
SELECT Product.type, Laptop.model, price
FROM Laptop INNER JOIN
     Product ON Laptop.model = Product.model
ORDER BY price DESC;
mssql
🚫
[[ error ]]
[[ column ]]
[[ value ]]
TypeModelprice
Laptop17501200
Laptop17521150
Laptop12981050
PC1233980
Laptop1321970
PC1233950
PC1121850
Laptop1298700
PC1232600
PC1233600
PC1232400
PC1232350
PC1260350

Suggested exercises: 7, 24, 26, 29, 30, 32, 36, 37, 41, 43, 44, 45, 48, 49, 51, 54, 56, 57, 102, 113, 131

Let’s consider the task.

Find out all available products of the producer ‘B’. Output: model, type.

One laptop and three PCs are in the database from maker ‘B’, and all the PCs are of the same model.

If we’ll use UNION ALL, we get all these items. Using UNION,  the duplicates will be excluded from the result:

select p.model, p.type from pc join Product p on PC.model=p.model where maker='B'
UNION ALL
select p.model, p.type from printer pr join Product p on pr.model=p.model where maker='B'
UNION ALL
select p.model, p.type from laptop lp join Product p on lp.model=p.model where maker='B';
mssql
🚫
[[ error ]]
[[ column ]]
[[ value ]]
modeltype
1121PC
1121PC
1121PC
1750Laptop
select p.model, p.type from pc join Product p on PC.model=p.model where maker='B'
UNION
select p.model, p.type from printer pr join Product p on pr.model=p.model where maker='B'
UNION
select p.model, p.type from laptop lp join Product p on lp.model=p.model where maker='B';
mssql
🚫
[[ error ]]
[[ column ]]
[[ value ]]
modeltype
1121PC
1750Laptop

The solution on the base of UNION corresponds to the somewhat different task, namely:

Find out which models of the maker ‘B’ are available. Output: model, type.