Sub topic 12
Joins on ranges and inequalities
Most joins compare two columns with =. The ON clause accepts any condition that evaluates to true or false, so you can also match rows by range or by comparison. This is called a non-equi join. This chapter assumes you can write an INNER JOIN ... ON query, use table aliases, and know that an inner join keeps only the row pairs for which the condition is true.
What changes when the condition is not equality
With an equality join on a primary key, each child row matches at most one parent row. A range or inequality condition gives no such guarantee. One row can match zero, one, or many rows on the other side.
The join still works the way you already know. Conceptually, the database considers pairs of rows and keeps the pairs where the ON condition is true. Only the shape of the condition differs.
Looking up a tier by range
A common use is a lookup table that stores ranges. Here is a small discount_tiers table, which the sample schema's orders can join to:
CREATE TABLE discount_tiers (
label VARCHAR(20) NOT NULL,
min_total DECIMAL(10, 2) NOT NULL,
max_total DECIMAL(10, 2) NOT NULL
);
INSERT INTO discount_tiers (label, min_total, max_total) VALUES
('Small', 0.00, 50.00),
('Medium', 50.00, 100.00),
('Large', 100.00, 1000.00);
SELECT o.id AS order_id, o.total, t.label
FROM orders AS o
INNER JOIN discount_tiers AS t
ON o.total >= t.min_total
AND o.total < t.max_total
ORDER BY o.id;The query returns four rows: order 101 (50.00) is Medium, 102 (75.00) is Medium, 103 (20.00) is Small, and 104 (99.00) is Medium.
The condition is written as a half-open range: the lower bound is inclusive (>=) and the upper bound is exclusive (<). Order 101 has a total of exactly 50.00. It falls in Medium, not Small, because Small stops just before 50.00.
Boundaries: why BETWEEN causes duplicates
BETWEEN a AND b is inclusive at both ends. If adjacent tiers share a boundary value, a row sitting on that boundary matches both tiers:
SELECT o.id AS order_id, o.total, t.label
FROM orders AS o
INNER JOIN discount_tiers AS t
ON o.total BETWEEN t.min_total AND t.max_total
ORDER BY o.id, t.label;Order 101 (total 50.00) now appears twice, once as Small (0 to 50) and once as Medium (50 to 100). Nothing raised an error. The join simply returned every pair that satisfied the condition.
Gaps and overlaps in the lookup data
An inner join only checks the condition. It does not check that your ranges are well formed. Two problems in the lookup table show up as wrong row counts:
| Problem in the range table | Effect on the inner join |
|---|---|
| Gap between ranges (for example 50 to 60 is not covered) | Orders in the gap match no tier and vanish from the result |
| Overlap between ranges | Orders in the overlap match several tiers and are duplicated |
| Open-ended top range stored as NULL | `total < NULL` is not true, so those orders vanish |
The last row connects to what you learned about NULL keys. Any comparison with NULL is unknown, and an inner join drops pairs whose condition is not true. If the top tier should have no upper limit, store a very large sentinel value, or write the condition as AND (t.max_total IS NULL OR o.total < t.max_total).
A quick check that every order got exactly one tier:
SELECT COUNT(*) AS orders_total,
(SELECT COUNT(*)
FROM orders AS o
INNER JOIN discount_tiers AS t
ON o.total >= t.min_total AND o.total < t.max_total) AS joined_rows
FROM orders;If joined_rows is larger than orders_total, you have overlaps. If it is smaller, you have gaps or NULL totals.
Date ranges
Ranges over dates follow the same pattern. A rate that changes over time is usually stored with an effective-from date and an effective-to date, and each fact is joined to the rate that was valid on its date:
CREATE TABLE tax_rates (
effective_from DATE NOT NULL,
effective_to DATE NOT NULL,
rate DECIMAL(4, 2) NOT NULL
);
INSERT INTO tax_rates (effective_from, effective_to, rate) VALUES
('2025-01-01', '2026-02-01', 0.20),
('2026-02-01', '9999-12-31', 0.22);
SELECT o.id AS order_id, o.order_date, r.rate, o.total * r.rate AS tax
FROM orders AS o
INNER JOIN tax_rates AS r
ON o.order_date >= r.effective_from
AND o.order_date < r.effective_to
ORDER BY o.id;Order 101 (January 5) gets 0.20. Orders 102, 103 and 104 get 0.22. The second row's start date equals the first row's end date, which is safe because the end is exclusive. The 9999-12-31 end date stands in for "no end yet", which avoids NULL.
Pairing rows of one table with each other
Inequalities are also how you build pairs from a single table. Joining a table to itself on equality finds rows that share a value. Adding < on the primary key keeps each pair once and stops a row from pairing with itself:
SELECT a.id AS first_order, b.id AS second_order, a.customer_id
FROM orders AS a
INNER JOIN orders AS b
ON b.customer_id = a.customer_id
AND a.id < b.id
ORDER BY a.id, b.id;The result is one row: orders 101 and 102, both from customer 1. With <> instead of <, you would also get (102, 101), so every pair would appear twice. With <=, every order would pair with itself as well. Order 104 has a NULL customer, so NULL = NULL is not true and it matches nothing.
Performance
An equality join can use an index on the joined column to find matches directly, or a hash join that builds a lookup table in memory. A range condition is harder for the database:
- Hash joins need equality, so a pure range join usually falls back to a nested loop, where the database tests each row from one side against candidate rows from the other.
- A B-tree index on
min_totaloreffective_fromcan narrow the candidate rows, but it can only use one end of the range efficiently. - With small lookup tables, such as a handful of tiers, none of this matters. With two large tables, an unselective inequality can approach the cost of a Cartesian product.
When a range join is slow, read the execution plan. Look for a nested loop with a full scan of the large table on the inner side, and compare the estimated row counts with the real ones. Adding an equality condition alongside the range (for example, joining on customer_id as well as a date range) lets the database use that equality to cut down the work first.
Summary of habits
- Write ranges as half-open intervals and join with
>=and<. - Avoid NULL as an "open end" marker in range columns.
- After writing the join, compare its row count with the count of the table you are looking up.
- For self-join pairs, use
a.id < b.idto get each unordered pair once.
Exercise
The tiers table has rows ('Small', 0, 50) and ('Medium', 50, 100). You join orders to it with ON o.total BETWEEN t.min_total AND t.max_total. An order has total 100.00 and the table also contains ('Large', 100, 1000). How many rows does this order produce, and how would you change the condition so it produces exactly one?
Show answer
It produces two rows, Medium (50 to 100) and Large (100 to 1000), because BETWEEN includes both endpoints and 100.00 sits on a shared boundary. Replace the condition with o.total >= t.min_total AND o.total < t.max_total. The order then matches only Large.
Exercise
You run a self join on orders with ON b.customer_id = a.customer_id AND a.id <> b.id. Customer 1 has orders 101 and 102. What rows does this return for customer 1, and why is a.id < b.id usually better?
Show answer
It returns (101, 102) and (102, 101), the same pair in both orders. a.id < b.id returns each pair once.