2.4

How to Code a UNION

How to Code a UNION

  • A UNION combines the results of two or more queries into a single result set
  • Each result set must have the same number of columns
  • The corresponding data types for each column must be compatible. However, the column names may be different from each result set
  • A UNION removes duplicate rows by default
  • You may interfile the results using an ORDERY BY clause if there is a column with a common name.

Code Example:

1 USE world;
2 SELECT name, population
3 FROM city WHERE CountryCode = 'AUS'
4 UNION
5 SELECT name, population
6 FROM country
7 WHERE continent = 'Oceania'
8 ORDER BY name; 

Results:

04_joins.png

SELECT name, population
FROM city
WHERE CountryCode = 'AUS'

UNION

SELECT name, population
FROM country
WHERE continent = 'Oceania'

ORDER BY name;

This content is provided to you freely by BYU-I Books.

Access it online or download it at https://books.byui.edu/learning_mysql/how_to_code_a_union.