Start learning free

LESSON 1 OF 66 · SQL: BEYOND THE BASICS

UNION: Two Queries, One List in Python

Practice

Sometimes the list you want comes from two tables. UNION runs two SELECTs and stacks their rows into one result: the rows of the second query go under the rows of the first. Both queries must give the same number of columns, and the result takes its column names from the first query.

A text in single quotes inside SELECT is a value, the same on every row. It makes a handy label that says where each row came from. UNION also drops duplicates: rows that are exact copies are kept once. UNION ALL keeps every row.

SELECT 'yes' AS answer
UNION
SELECT 'yes'
-- 1 row: yes

SELECT 'yes' AS answer
UNION ALL
SELECT 'yes'
-- 2 rows: yes, yes

Each query keeps its own FROM and WHERE: a WHERE under the second query filters only that query's rows. In the shop, two customers live in Cluj, and one product has no category (NULL). Your query must print:

kind | name
category | home
category | kitchen
category | office
city | Berlin
city | Cluj
city | Madrid
city | Rome
(7 rows)

Your task: in query, select the label 'city' as kind and city as name from customers. Below it, with UNION, select the label 'category' and category from products, leaving out the product with no category.


Assignment
Follow the Coding Tutorial to build query, one clause per line, each in its own string.


Hint
The second SELECT needs no AS: the column names come from the first one. Its WHERE category IS NOT NULL goes right under FROM products.


STEP 1 OF 6
    Ctrl + Enter to check

    Sqlx Union in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free