Interview Puzzles · Problem 98 of 118

Same City, Same Day

HardInterview PuzzlesShop data

Return pairs of customers with the same joined_on date who live in the same city (ignoring case). Return customer_a, customer_b (their ids, with customer_a smaller than customer_b) and joined_on. Sort by joined_on, then customer_a, then customer_b.

Hint 1

Join customers to itself.

Hint 2

a.customer_id < b.customer_id removes pairs that pair a customer with itself and the mirrored pair (b, a).

Reference solution

SELECT a.customer_id AS customer_a,
       b.customer_id AS customer_b,
       a.joined_on
FROM customers AS a
JOIN customers AS b
  ON a.joined_on = b.joined_on
 AND LOWER(a.city) = LOWER(b.city)
 AND a.customer_id < b.customer_id
ORDER BY a.joined_on, customer_a, customer_b;

In a self join every pair can be matched in both directions: (1, 2) and (2, 1). Using < instead of <> keeps one direction only and also rules out matching a row with itself. This "pairs" pattern is used for finding duplicates, overlaps, conflicts between bookings, and pairs of events close in time.