Consider two tables Employees and Departments:
Employees:
id | name | dept_id
1 | Alice | 10
2 | Bob | NULL
3 | Carol | 20
Departments:
dept_id | dept_name
10 | Sales
20 | HR
NULL | Unknown
What will be the result of this query?
SELECT e.name, d.dept_name
FROM Employees e
INNER JOIN Departments d ON e.dept_id = d.dept_id;
SELECT e.name, d.dept_name FROM Employees e INNER JOIN Departments d ON e.dept_id = d.dept_id;
Remember that = comparison with NULL does not return true in SQL.
In SQL, NULL = NULL is not true, so rows with NULL in join columns do not match in INNER JOIN. Only rows with matching non-NULL values join.
Using the same tables Employees and Departments as before, what is the output of this query?
SELECT e.name, d.dept_name
FROM Employees e
LEFT JOIN Departments d ON e.dept_id = d.dept_id;
SELECT e.name, d.dept_name FROM Employees e LEFT JOIN Departments d ON e.dept_id = d.dept_id;
LEFT JOIN keeps all rows from the left table, even if no match is found on the right.
Bob's dept_id is NULL, so no matching department row is found. LEFT JOIN returns Bob's row with dept_name as NULL.
Why does a join condition like table1.col = table2.col fail to match rows when either column contains NULL?
Think about how SQL treats NULL in logical comparisons.
In SQL, NULL means unknown. Any comparison with unknown results in unknown, which is treated as false in WHERE or JOIN conditions.
Which SQL join condition correctly matches rows where columns may be NULL, treating NULLs as equal?
Think about how to explicitly check for NULL equality in SQL.
Since = does not treat NULLs as equal, adding OR (col1 IS NULL AND col2 IS NULL) handles NULL-safe equality.
You have two large tables with millions of rows each, and you want to join them on columns that may contain NULLs, treating NULLs as equal. Which approach is most efficient?
Consider how indexes and functions affect query performance.
Using COALESCE allows the join to use indexes if the columns are indexed, improving performance over OR conditions which often disable index use.