Joins · Problem 55 of 118

Countries We Touch

MediumJoinsShop data

Return every country that appears in customers or in suppliers, once each, sorted alphabetically.

Hint 1

UNION combines two queries with the same number of columns and removes duplicate rows.

Reference solution

SELECT country FROM customers
UNION
SELECT country FROM suppliers
ORDER BY country;

UNION stacks the rows of two queries and removes duplicates; UNION ALL keeps them (and is faster, because it does not need to compare rows). Both queries need the same number of columns with compatible types. ORDER BY goes once, at the very end, and applies to the whole combined result.

Another way. UNION ALL keeps duplicates; wrapping it in SELECT DISTINCT gives the same result as UNION.

SELECT DISTINCT country
FROM (SELECT country FROM customers UNION ALL SELECT country FROM suppliers)
ORDER BY country;