BBampaa

Lessons › SQL › Chapter 5: Joins, subqueries and CTEs

SQL lesson

UNION and UNION ALL

A JOIN puts tables side by side. UNION puts them on top of each other: the rows from the second query go under the rows from the first. UNION ALL keeps every row, repeats too. UNION shows each row only once.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Stack two lists into one

SELECT customer_id
FROM online_orders
UNION ALL
SELECT customer_id
FROM store_sales

Result:

customer_id
C101
C102
C103
C102
C106

Step by step

  1. Puts the second list under the first. Every row stays. Both lists need the same columns, in the same order.
    SELECT customer_id FROM online_orders UNION ALL SELECT customer_id FROM store_sales
  2. The same, but a row in both lists shows once.
    SELECT customer_id FROM online_orders UNION SELECT customer_id FROM store_sales ORDER BY customer_id

Practice

Try each one in your head first, then open the answer.

1. Using online_orders and store_sales, list every customer_id from both, keeping repeats.
SELECT customer_id FROM online_orders UNION ALL SELECT customer_id FROM store_sales
2. Show channel and revenue from online_orders and from store_sales in one list, keeping repeats.
SELECT channel, revenue FROM online_orders UNION ALL SELECT channel, revenue FROM store_sales

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed