Non-Equi Joins (Joining on Ranges, Dates & Inequalities)
Join on ranges and inequalities for slowly changing dims and overlapping intervals.
In plain words
Instead of matching equal values, match a value to the range it fits in, or match things that overlap.
Think of it like…
Assigning exam scores to grades using a table of ranges (90–100 is A, 80–89 is B): you don't look up an exact score, you find the range it falls into.
Where you’ve seen it
Applying shipping charges by order weight: SELECT o.id, r.charge FROM orders o JOIN shipping_rates r ON o.weight_kg >= r.min_kg AND o.weight_kg < r.max_kg; and finding double-booked rooms: JOIN bookings b2 ON b1.room_id = b2.room_id AND b1.id < b2.id AND b1.check_in < b2.check_out AND b2.check_in < b1.check_out.
Words you’ll hear
- Range join
- Matching a value to the range [start, end) that contains it.
- Overlap condition
- a.start < b.end AND b.start < a.end.
- Half-open range
- >= start AND < end, so boundary values match exactly one range.
- Range types
- PostgreSQL tstzrange / int4range with && and @> operators and GiST indexes.
Visual diagram
Theory & example queries
Ranges, intervals and overlaps
For brackets and price lists, store each range's lower and upper bound and join with value >= lower AND value < upper. Use half-open ranges so a value on a boundary (exactly 1 kg) matches exactly one band; with inclusive BETWEEN at both ends, it would match two. Check the range table for overlaps and gaps, because overlaps duplicate rows and gaps silently drop them (catch those with a LEFT JOIN).
Two intervals overlap when each starts before the other ends: a.start < b.end AND b.start < a.end. This one condition covers every overlap case: partial, containing and contained. For pairs within the same table, add a.id < b.id to avoid matching a row with itself and listing each pair twice.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT o.id, p.priceFROM orders o JOIN price_history p ON p.product_id = o.product_id AND o.ordered_at >= p.valid_from AND ( o.ordered_at < p.valid_to OR p.valid_to IS NULL );PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative effective prices3 sample rows
| id | price |
|---|---|
| 801 | 499 |
| 802 | 549 |
| 803 | 549 |
Note: Sample data assumes one non-overlapping price-history interval for each order's product on ordered_at; overlapping periods would return multiple rows.
Key takeaway: Half-open ranges; overlap = each starts before the other ends.
Making range joins fast
Hash and merge joins need equality conditions, so a join on inequalities alone falls back to a nested loop, comparing every row with every row in the worst case. Adding an equality condition (product_id, room_id) narrows each comparison to a small group, and an index on (key, start) helps the inner side.
PostgreSQL's range types make this cleaner and faster: store tstzrange(check_in, check_out), query with && (overlaps) or @> (contains), and index with GiST. An exclusion constraint, EXCLUDE USING gist (room_id WITH =, stay WITH &&) (with the btree_gist extension), lets the database itself prevent double bookings.
CREATE EXTENSION IF NOT EXISTS btree_gist;ALTER TABLE bookingsADD CONSTRAINT no_double_booking EXCLUDE USING gist ( room_id WITH =, tstzrange (check_in, check_out) WITH &&);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Representative command responses2 sample rows
| statement | status |
|---|---|
| CREATE EXTENSION | CREATE EXTENSION |
| ALTER TABLE | ALTER TABLE |
Note: PostgreSQL returns these statuses when the extension and constraint are created successfully. Validation fails if existing bookings already overlap.
Key takeaway: Pair inequalities with an equality key; use range types and GiST for heavy use.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Model ranges with two bounds
Store lower and upper bounds (or a range type) and decide that upper bounds are exclusive.
min_kg (inclusive), max_kg (exclusive)
When to use it & trade-offs
What it is
A non-equi join matches rows on a condition other than equality: a range (o.amount BETWEEN b.min_amount AND b.max_amount), an inequality (a.price < b.price), or overlapping time intervals. It's how you assign values to brackets, match events to the period they fall in, and find overlaps or pairs within a time window.
Why it matters: Tax slabs, shipping-rate tables, price lists valid between two dates, and "bookings that overlap" all need range joins. They're also slower than equality joins, because hash and merge joins can't be used for pure inequalities, which matters on large tables.
When to reach for it
- Tax slabs, shipping bands and pricing tiers
- Matching events to the period or price valid at the time
- Finding overlapping bookings or shifts
When to avoid or be careful
- Inclusive bounds on both ends of adjacent ranges
- Range joins on huge tables with no equality key or index
- Assuming every value matches a band without a LEFT JOIN check
Range join vs equality join vs range types
Strengths: Works in every database.
Watch out: Nested-loop plans; overlaps or gaps cause wrong counts.
Strengths: Hash joins and simple indexes.
Watch out: Only works when the band can be derived exactly.
Strengths: && and @> operators, indexes, exclusion constraints.
Watch out: PostgreSQL-specific.
Interview signals & numbers to know
When this topic comes up
- “Apply the tax slab to each salary”
- “Which price was valid on the order date?”
- “Find overlapping bookings”
- BETWEEN in a JOIN
- SCD Type 2 lookups
Benchmarks & rules of thumb
- [start, end)
- half-open range
- 2
- comparisons in the overlap test
- 0
- hash joins possible on inequality-only conditions
Common mistakes & follow-ups
Common interview mistakes
- Using BETWEEN on adjacent bands so boundary values match two bands.
- Writing an overlap test with four OR-ed cases instead of a.start < b.end AND b.start < a.end.
- Self-joining bookings without a.id < b.id, matching each booking with itself.
Likely interviewer follow-ups
- How do you check whether two time intervals overlap?
- How would you assign each order to a shipping-rate band?
- How can PostgreSQL prevent double bookings at the database level?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Non-Equi Joins (Joining on Ranges, Dates & Inequalities) with hands-on SQL practice and interview Q&A.