DevPath · Learn to code ESPTEN

Sets and functions

Set operations

Working with sets of rows

So far each query produced one result. Set operators combine the results of two SELECT statements as if they were mathematical sets. They are written between the two queries:

SELECT name FROM products
UNION
SELECT name FROM clearance;

Rules common to all of them

To combine two queries, both must have:

The result's column names come from the first query.

UNION vs UNION ALL

SELECT category FROM products
UNION ALL
SELECT category FROM clearance;

INTERSECT and EXCEPT

SELECT name FROM products
INTERSECT
SELECT name FROM clearance;   -- products that are also on clearance

Like UNION, the INTERSECT and EXCEPT operators also remove duplicates by default.

ORDER BY in combinations

An ORDER BY applies to the whole result of the combination, so it goes at the end, after the last query (not inside each SELECT):

SELECT name FROM products
UNION
SELECT name FROM clearance
ORDER BY name;        -- sorts the ENTIRE combined result

Examples

UNION removes duplicates; UNION ALL keeps them

SELECT category FROM products
UNION
SELECT category FROM clearance
ORDER BY category;
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Working with NULL →