Start learning free

LESSON 2 OF 66 · SQL: BEYOND THE BASICS

Join a Table to Itself in Python

Practice

A join doesn't need two different tables. To pair a row with another row of the same table, you read the table twice, under two names. A name right after the table, a table alias, says which copy you mean: customers a and customers b are the same rows, read twice.

SELECT cheap.name, dear.name
FROM products cheap
JOIN products dear ON cheap.price < dear.price

This query pairs each product with every product that costs more. Joining on an equal value, like the same city, has a catch: every row also matches itself, and each pair comes twice, once as (Ana, Chloe) and once as (Chloe, Ana). Adding a.id < b.id to the condition fixes both: an id is never smaller than itself, and of the two orders of a pair, only one has the smaller id first.

Before your query runs, the check adds two customers: Felix Braun in Berlin (id 6) and Gina Marin in Cluj (id 7). Your query must print:

name_a | name_b | city
Ana Pop | Chloe Ng | Cluj
Ana Pop | Gina Marin | Cluj
Chloe Ng | Gina Marin | Cluj
Dan Weber | Felix Braun | Berlin
(4 rows)

Your task: in query, list every pair of customers who live in the same city, each pair once: a.name as name_a, b.name as name_b, and a.city.


Assignment
Follow the Coding Tutorial to join customers to itself, one clause per line, each in its own string.


Hint
Name the table a after FROM and b after JOIN. The join condition has two parts: a.city = b.city, then AND a.id < b.id on the next line.


STEP 1 OF 4
    Ctrl + Enter to check

    Sqlx Self Join 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