Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 50/ 160
03. Joins & Relational Querying

Non-Equi Joins (Joining on Ranges, Dates & Inequalities)

Join on ranges and inequalities for slowly changing dims and overlapping intervals.

AdvancedRange Join · Inequality Predicates3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

The price valid on the order dateQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  o.id,3  p.price4FROM5  orders o6  JOIN price_history p ON p.product_id = o.product_id7  AND o.ordered_at >= p.valid_from8  AND (9    o.ordered_at < p.valid_to10    OR p.valid_to IS NULL11  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative effective prices3 sample rows
Representative effective prices
idprice
801499
802549
803549

Note: Sample data assumes one non-overlapping price-history interval for each order's product on ordered_at; overlapping periods would return multiple rows.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Preventing overlapping bookings (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE EXTENSION IF NOT EXISTS btree_gist;23ALTER TABLE bookings4ADD CONSTRAINT no_double_booking EXCLUDE USING gist (5  room_id6  WITH7    =,8    tstzrange (check_in, check_out)9  WITH10    &&11);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command responses2 sample rows
Representative command responses
statementstatus
CREATE EXTENSIONCREATE EXTENSION
ALTER TABLEALTER TABLE

Note: PostgreSQL returns these statuses when the extension and constraint are created successfully. Validation fails if existing bookings already overlap.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Pair inequalities with an equality key; use range types and GiST for heavy use.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Model ranges with two bounds

Store lower and upper bounds (or a range type) and decide that upper bounds are exclusive.

Focus at this step

min_kg (inclusive), max_kg (exclusive)

What to watch at this step
Half-open
[min, max)
Tip: use ← → to move between steps

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

Range join with >= and <
Best for: Brackets, price lists, date-valid records

Strengths: Works in every database.

Watch out: Nested-loop plans; overlaps or gaps cause wrong counts.

Equality join on a precomputed key
Best for: Fixed bands you can compute (FLOOR(weight))

Strengths: Hash joins and simple indexes.

Watch out: Only works when the band can be derived exactly.

PostgreSQL range types + GiST
Best for: Bookings, schedules, validity periods at scale

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?
Interview tip: Write the overlap condition from memory (each starts before the other ends) and mention half-open ranges. Interviewers often ask for exactly that.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
SELF JOIN for Hierarchical & Peer Comparisons
Next topic
NATURAL JOIN & USING Clause (and Why to Avoid NATURAL JOIN)