• Learning MySQL By Example
  • Introduction
  • 1. How to Retrieve Data From a Single Table
  • 2. How to Retrieve Data from Multiple Tables
  • 3. Using Functions
  • 4. How to Insert, Update, Delete Data in Tables
  • 5. Summary Queries and Aggregate Functions
  • 6. Working With Subqueries
  • 7. SQL Views
  • 8. SQL Indexes
  • Glossary
  • Index
  • Download
  • Translations
  • 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 EdTech Books.

    Access it online or download it at https://edtechbooks.org/learning_mysql/how_to_code_a_union.