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'
5 SELECT name, population
6 FROM country
7 WHERE continent = 'Oceania'
8 ORDER BY name; 



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


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

ORDER BY name;

CC BY-NC-ND International 4.0

CC BY-NC-ND International 4.0: This work is released under a CC BY-NC-ND International 4.0 license, which means that you are free to do with it as you please as long as you (1) properly attribute it, (2) do not use it for commercial gain, and (3) do not create derivative works.

End-of-Chapter Survey

: How would you rate the overall quality of this chapter?
  1. Very Low Quality
  2. Low Quality
  3. Moderate Quality
  4. High Quality
  5. Very High Quality
Comments will be automatically submitted when you navigate away from the page.
Like this? Endorse it!