JOIN Conditions & Pitfalls
8. JOIN Conditions & Pitfalls
Section titled “8. JOIN Conditions & Pitfalls”Non-equi joins
Section titled “Non-equi joins”Joins don’t have to use =. Any comparison operator works:
-- Find employees whose salary falls within a salary bandSELECT e.name, sb.band_nameFROM employees eJOIN salary_bands sb ON e.salary BETWEEN sb.min_sal AND sb.max_sal;Multiple conditions
Section titled “Multiple conditions”You can combine conditions with AND:
SELECT e.name, p.project_nameFROM employees eJOIN assignments a ON e.id = a.employee_id AND a.active = 1JOIN projects p ON a.project_id = p.id;NULL behavior
Section titled “NULL behavior”NULL never equals anything — not even another NULL. This matters in joins:
-- This join will NEVER match Carol (dept_id = NULL)ON e.dept_id = d.dept_id -- NULL = anything → UNKNOWN → no matchPerformance tips
Section titled “Performance tips”- Always join on indexed columns. Foreign keys should have indexes.
- Filter early: push
WHEREconditions as close to the source tables as possible. - Avoid joining on expressions:
ON YEAR(e.hire_date) = 2020cannot use an index. Instead, filter withWHEREafter joining.