Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Preview

AC 2.1: Stacking two lists with UNION

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

45 minutes

Two lists, one list

The shop has a list of products it sells today. It also has a list of products it used to sell. The manager wants one list of every name, with no repeats.

You could copy one list under the other and delete the repeats by hand. Or you could ask the computer to stack them.

Key words

WordWhat it means
Databasean organised store of tables that you can ask questions
SQLthe language used to ask a database for data
Queryone question written in SQL
UNIONstacks the rows of two queries into one answer and removes repeats
UNION ALLstacks the rows of two queries and keeps every repeat
Duplicatea row that appears more than once

The cells students fill in are left blank in this preview.

By the end of this lesson

Note

I can join two queries with UNION and UNION ALL, and say what the rules are.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Try it: stack two lists

Code: sql
SELECT name FROM products
UNION
SELECT name FROM old_products
ORDER BY name;

-- Apple is in both lists. Count it in the answer.

Three rules for UNION

  1. Both queries must give the same number of columns.
  2. Matching columns must hold the same kind of value.
  3. The column names come from the first query.

ORDER BY goes once, at the very end, and sorts the whole stack.

Worked example: UNION against UNION ALL

QueryRows from productsRows from old_productsRows in answer
UNION10413 (Apple appears once)
UNION ALL10414 (Apple appears twice)

The cells students fill in are left blank in this preview.

Try it: keep the repeats

Code: sql
SELECT name FROM products
UNION ALL
SELECT name FROM old_products
ORDER BY name;

-- Compare with the UNION answer. Which name appears twice?

Check

Have a go

Check

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

The lesson goes on

5 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.