Practical SQL

NON-EQUI joins in SQL

Constantin LunguUpdated 1 min read

Photo by Julia Taubitz on Unsplash

So here's another post about SQL joins. Based on the type of condition we use for joining we distinguish equi joins and non-equi joins.

Simply put:
- equi joins: we're using the equality operator:
tab_a.column_x = tab_b.column_y
- non-equi joins: other operators, like comparison, inequality or BETWEEN are used

While a good portion of the time we use equi joins to, say, lookup the department the employee is part of, non-equi joins are not uncommon either.

Moreover, sometimes we might use both equality and other operators for joining the same table.

Let's look at a simple non-equi join scenario below.

Input data: campaigns (Winter 2021, Summer 2021, Winter 2022, Summer 2022 with valid_from/valid_to half-year ranges), discounts (0-50 at 0.1, 50-100 at 0.15, 100-1000000 at 0.2) and orders (1 on 2021-03-01 for 100, 2 on 2022-03-01 for 45, 3 on 2022-07-01 for 151, 4 on 2022-12-01 for 80).

SELECT
  o.order_id,
  o.order_date,
  c.name AS campaign_name,
  o.amount AS list_price_amount,
  d.discount_percentage,
  (1-discount_percentage)*amount AS paid_amount
FROM orders o
JOIN campaign c ON o.order_date BETWEEN c.valid_from AND c.valid_to
JOIN discounts d ON o.amount >= value_from AND o.amount < value_to

Results: order 4 (2022-12-01, Summer 2022, 80) gets 0.15 and pays 68; order 3 (2022-07-01, Summer 2022, 151) gets 0.2 and pays 120.8; order 2 (2022-03-01, Winter 2022, 45) gets 0.1 and pays 40.5; order 1 (2021-03-01, Winter 2021, 100) gets 0.2 and pays 80.


Enjoyed this? Here are some related articles you might find useful: