Menu
Coddy logo textTech

Union

Part of the Fundamentals section of Coddy's SQL journey — lesson 48 of 72.

Unions are different from joins. Joins are using conditions to combine tables but unions just add two tables on top of the other. To use UNION we will write:

SELECT col1, col2, ... FROM table1
UNION
SELECT col1, col2, ... FROM table2

Both selects must obey the following rules:

  • The number of fields should be equal
  • Order is important
  • The columns in the same place must match the data types

For example, let's assume we have the following tables:

germany_people

idname
1Lena
2Leonie

england_people

idname
1George
2Lena

Problem: We want to make one big table of all the names we have.

SELECT name from germany_people
UNION
SELECT name from england_people

Result:

name
Lena
Leonie
George

UNION returns only distinct values while UNION ALL return all of the records as-is:

SELECT name from germany_people
UNION ALL
SELECT name from england_people

Result:

name
Lena
Leonie
George
Lena

You can also combine UNION ALL with aggregate functions, GROUP BY, and ORDER BY to summarize data across multiple tables. The trick is to wrap the UNION ALL inside a subquery, then apply grouping and sorting on top of it.

For example, suppose we want to count how many times each name appears across both tables:

SELECT name, COUNT(*) AS total_count
FROM (
    SELECT name FROM germany_people
    UNION ALL
    SELECT name FROM england_people
) AS combined
GROUP BY name
ORDER BY total_count DESC

Result:

nametotal_count
Lena2
Leonie1
George1

Here, UNION ALL (not UNION) is used so that duplicates like Lena are kept — otherwise they would be removed before counting. The subquery merges all rows, and then GROUP BY + COUNT summarize them. ORDER BY sorts the final result.

challenge icon

Challenge

Easy

Available tables and columns:

  • <strong>sales_2009</strong>: <strong>product_id</strong>, <strong>quantity_sold</strong>
  • <strong>sales_2010</strong>: <strong>product_id</strong>, <strong>quantity_sold</strong>
  • <strong>sales_2011</strong>: <strong>product_id</strong>, <strong>quantity_sold</strong>

There are 3 sales tables.

Find the sum of sales for each product of all tables together.

The result should include the product_id and the total sales.

Name this column total_sales.

Sort the results by the total sales in descending order.

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals