UNION Operator in SQL

Level 4114 keystrokes

UNION stacks the results of two SELECT statements and removes duplicate rows; here customer and supplier names are combined, each labelled with its type, and sorted by name.

SQL code

-- First query: every customer name
1SELECT
2 name,
-- A constant column that labels these rows 'customer'
3 'customer' AS type
4FROM
5 customers
-- UNION appends the second result and removes rows that are exactly the same
-- Both SELECTs must return the same number of columns
6UNION
-- Second query: every supplier name
7SELECT
8 name,
-- Labels these rows 'supplier', so a name in both tables still gives two rows
9 'supplier' AS type
10FROM
11 suppliers
-- ORDER BY sorts the combined result, not just the second query
12ORDER BY
-- Alphabetical order: Acme, Alice, Bob, Parts
13 name;

Output

+-------+----------+
| name  | type     |
+-------+----------+
| Acme  | supplier |
| Alice | customer |
| Bob   | customer |
| Parts | supplier |
+-------+----------+
4 rows in set
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this SQL code and how often they appear.

  • '× 4
  • ,× 2
  • ;× 1

More SQL examples at level 4

← SQL typing practice