Non-Equi Joins are an advanced SQL concept that allows joining tables based on conditions other than equality (=). These joins use operators such as >, <, >=, <=, !=, and BETWEEN to match rows from two tables.
A Non-Equi Join is a type of join that combines rows from two or more tables based on a non-equality condition. Unlike an equi join, which strictly matches rows using the equality operator (=
), a Non-Equi Join allows for more complex relationships between tables.
=
in the join condition.
SELECT columns
FROM Table1 t1
JOIN Table2 t2
ON t1.column1 t2.column2;
<operator>
: Any comparison operator (<
, >
, <=
, >=
, !=
, BETWEEN
, etc.).>
OperatorScenario: Match employees with salaries greater than a threshold.
EmployeeID | Name | Salary |
---|---|---|
1 | Alice | 50000 |
2 | Bob | 60000 |
3 | Charlie | 70000 |
ThresholdID | Threshold |
---|---|
1 | 55000 |
SELECT e.Name, e.Salary, t.Threshold
FROM Employees e
JOIN SalaryThresholds t
ON e.Salary > t.Threshold;
Name | Salary | Threshold |
---|---|---|
Bob | 60000 | 55000 |
Charlie | 70000 | 55000 |
55000
are included in the result.BETWEEN
OperatorScenario: Find orders within a specific date range.
OrderID | OrderDate |
---|---|
1 | 2024-01-01 |
2 | 2024-02-15 |
3 | 2024-03-10 |
RangeID | StartDate | EndDate |
---|---|---|
1 | 2024-01-01 | 2024-02-28 |
SELECT o.OrderID, o.OrderDate, r.StartDate, r.EndDate
FROM Orders o
JOIN DateRanges r
ON o.OrderDate BETWEEN r.StartDate AND r.EndDate;
OrderID | OrderDate | StartDate | EndDate |
---|---|---|---|
1 | 2024-01-01 | 2024-01-01 | 2024-02-28 |
2 | 2024-02-15 | 2024-01-01 | 2024-02-28 |
2024-01-01
and 2024-02-28
are retrieved.!=
OperatorScenario: Find mismatched product categories.
ProductID | CategoryID |
---|---|
1 | A |
2 | B |
ExclusionID | ExcludedCategory |
---|---|
1 | A |
SELECT p.ProductID, p.CategoryID, e.ExcludedCategory
FROM Products p
JOIN ExcludedCategories e
ON p.CategoryID != e.ExcludedCategory;
ProductID | CategoryID | ExcludedCategory |
---|---|---|
2 | B | A |
WHERE
clauses to reduce the dataset before the join.EXPLAIN
to understand query performance.Scenario: Match sales to commissions based on sales ranges.
SaleID | Amount |
---|---|
1 | 300 |
2 | 700 |
3 | 1500 |
RangeStart | RangeEnd | CommissionRate |
---|---|---|
0 | 500 | 5% |
501 | 1000 | 7% |
1001 | 2000 | 10% |
SELECT s.SaleID, s.Amount, c.CommissionRate
FROM Sales s
JOIN Commissions c
ON s.Amount BETWEEN c.RangeStart AND c.RangeEnd;
SaleID | Amount | CommissionRate |
---|---|---|
1 | 300 | 5% |
2 | 700 | 7% |
3 | 1500 | 10% |
Non-Equi Joins provide powerful tools for handling complex relationships between tables, especially when equality-based joins are insufficient. They enable advanced queries for scenarios like range matching, thresholds, and hierarchical data. Happy Coding!❤️