Articles

SQL union of several queries

The UNION clause makes it possible to add the result of two or more queries. Exactly as if we were doing only one query from several separate queries.

select statement 1
UNION
select statement 2
UNION
select statement 3
…

In addition, the UNION clause naturally eliminates the resulting duplicates.

Conditions of use

SELECTs must contain the same number of columns. The columns must be, respectively, between the selects, of the same type of data. Only one ORDER BY clause is allowed, obligatorily at the end. If an ORDER BY clause is present, it must use the column numbers and not their name.

Provide a price list, in order of product numbers, where the cost of products
belonging to class A15 is increased by 10% and the cost of other products is
increased by 15%.

SELECT product_code, cost * 1.1 AS price
FROM product
WHERE class = 'A15'
UNION
SELECT product_code, cost * 1.15
FROM product
WHERE class <> 'A15' ORDER BY 1;

Move to the next article: Data Definition Language DDL