Skip to the content

Neighbors who don't know it

Problem

The store wants to offer shared deliveries: two customers in the same city can get their orders in a single trip. For that it needs the list of possible pairs.

For each pair of customers who live in the same city, show the city and the two names, with the name of whoever has the lower id first. Each pair shows up only once, and nobody is paired with themselves. Someone with no city on file isn't anybody's neighbor.

What it has to return

These rows, in any order

citycustomerneighbor
DenverAnnBrian
DenverAnnValerie
AustinLukeHannah
DenverValerieBrian

This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.

You start with this

SQL

SELECT c.city,
  c.name AS customer,
  n.name AS neighbor
FROM customers c
JOIN customers n
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n log n) challenges

See all challenges →