Self Joins and Non-Equi Joins

INNER JOIN and outer joins paired two different tables with =. Joins take other forms too.

FormHow rows are pairedUses
Self joinRows of the same table with each otherCustomers who joined on the same day, other orders of the same customer
Non-equi joinA condition other than = (BETWEEN, <, >)Mapping values to ranges, counting larger values

Self join: two aliases

Write the same table twice in FROM and tell them apart by alias. Without aliases, customers.cust_id cannot be resolved to either side, which is an error.

Find other customers with the same join date (join_dt). a is the base customer and b is the paired customer.

Other customers who joined on the same day

SELECT a.cust_id, a.join_dt, b.cust_id AS same_day_cust
FROM customers a
JOIN customers b
  ON b.join_dt = a.join_dt
 AND b.cust_id <> a.cust_id
WHERE a.cust_id BETWEEN 1 AND 3
  AND b.cust_id <= 6000
ORDER BY a.cust_id, b.cust_id

There are 9 rows, 3 per customer. In this sample data, customer IDs that differ by 1800 have the same join date. Without b.cust_id <> a.cust_id, each customer also pairs with itself (1 and 1).

Pitfall: the same pair appears twice

Counting "pairs of customers who joined on the same day" with a self join yields (1, 1801) and (1801, 1) separately. Compare the pair counts per condition.

Comparing pair counts (customers 1-3600)

SELECT COUNT(*)                                          AS all_pairs,
       SUM(CASE WHEN a.cust_id =  b.cust_id THEN 1 ELSE 0 END) AS self_pairs,
       SUM(CASE WHEN a.cust_id <> b.cust_id THEN 1 ELSE 0 END) AS both_orders,
       SUM(CASE WHEN a.cust_id <  b.cust_id THEN 1 ELSE 0 END) AS unique_pairs
FROM customers a
JOIN customers b ON b.join_dt = a.join_dt
WHERE a.cust_id <= 3600
  AND b.cust_id <= 3600

Customers 1-3600 have 2 customers per join date. The result is:

ConditionPairsWhat is included
None7200Self pairs, (1, 1801), (1801, 1)
a.cust_id <> b.cust_id3600(1, 1801), (1801, 1)
a.cust_id < b.cust_id1800(1, 1801)

To count each pair once, use < instead of <>. The side with the smaller key is always a, so both self pairs and pairs that differ only in order are removed.

Pairing only once

SELECT a.cust_id, b.cust_id AS pair_cust, a.join_dt
FROM customers a
JOIN customers b
  ON b.join_dt = a.join_dt
 AND b.cust_id > a.cust_id
WHERE a.cust_id IN (1, 2, 1801, 1802, 3601, 3602)
  AND b.cust_id IN (1, 2, 1801, 1802, 3601, 3602)
ORDER BY a.join_dt, a.cust_id, b.cust_id

There are 3 customers per join date, so 3 × 2 / 2 = 3 pairs each, 6 rows in total.

Non-equi self join: counting larger values

A join condition can combine = with an inequality. Count the orders of the same customer with a larger amount. The largest order gets 0.

Number of larger orders (customer 101)

SELECT o1.ord_id, o1.amt, COUNT(o2.ord_id) AS bigger_orders
FROM orders o1
LEFT JOIN orders o2
  ON o2.cust_id = o1.cust_id
 AND o2.amt > o1.amt
WHERE o1.cust_id = 101
GROUP BY o1.ord_id, o1.amt
ORDER BY o1.amt DESC

The largest order has no match, so LEFT JOIN keeps it. If the customer has n orders, there are n × n comparisons. If the goal is a ranking, RANK() from window functions gives the same values with a single sort.

Non-equi join: mapping to a range table

To split amounts into ranges, keep the ranges in a table and join with >= and <. Here VALUES builds the range table. Each range includes its start and excludes its end.

Orders per amount range (customers 101-200)

SELECT b.band, b.lo, b.hi, COUNT(*) AS orders
FROM orders o
JOIN (VALUES ('LOW',       0, 100000),
             ('MID',  100000, 300000),
             ('HIGH', 300000, 1000000)) AS b(band, lo, hi)
  ON o.amt >= b.lo
 AND o.amt <  b.hi
WHERE o.cust_id BETWEEN 101 AND 200
GROUP BY b.band, b.lo, b.hi
ORDER BY b.lo

The same can be done with CASE WHEN amt < 100000 THEN 'LOW' …. With a range table, changing the ranges means editing data, not the query. A non-equi join cannot use a hash join, so on large tables the join method decides performance (Range join: NL vs sort merge).

NOTE Because this is an INNER JOIN, values that fall in no range (here, below 0 or 1,000,000 and above) drop out of the result. To check the dropped rows, change it to LEFT JOIN and look at rows where b.band IS NULL.

Pitfall: BETWEEN and range boundaries

BETWEEN lo AND hi includes both ends. If one range's end equals the next range's start, the boundary value falls into both ranges and rows multiply.

Boundary value 100000 appearing twice

SELECT v.amt, b.band
FROM (VALUES (99999), (100000), (100001)) AS v(amt)
JOIN (VALUES ('LOW',       0, 100000),
             ('MID',  100000, 300000)) AS b(band, lo, hi)
  ON v.amt BETWEEN b.lo AND b.hi
ORDER BY v.amt, b.band

Three values become 4 rows. 100000 falls into both LOW and MID.

Range conditionBoundary handling
amt >= lo AND amt < hiA boundary value falls only into the next range.
amt BETWEEN lo AND hiRanges must be written without overlap, such as 0-99999, 100000-299999. Non-integer values (an amount of 99999.5, a date with a time) fall into the gaps.

TIP Date ranges are the same. Using BETWEEN start_date AND end_date on a column with a time, such as ord_dt, includes only up to midnight of the end date, so orders after midnight that day are dropped. Write ord_dt >= start_date AND ord_dt < day after end_date.