— TodayIRevisited, SQL, Programming — 1 min read
This is a common one that has probably bitten every person who has ever used SQL. When one defines a where predicate on a SQL statement, only values that evaluate to true against the predicate AND are not null will be returned.
For example, if we have the following data in the dim_department table:
| department_name | employee_count |
|---|---|
| compliance | NULL |
| legal | 1 |
| it | 3 |
| finance | 5 |
And you run the following query against the table:
1SELECT2 department_name,3 employee_count4FROM dim_department5WHERE employee_count >= 06;We will only get three rows back:
| department_name | employee_count |
|---|---|
| legal | 1 |
| it | 3 |
| finance | 5 |
The row where department_name = 'compliance' will be excluded from the result set. We must explicitly add a null-inclusion statement to the predicate to get back this row:
1SELECT2 department_name,3 employee_count4FROM dim_department5WHERE employee_count >= 06OR employee_count IS NULL7;Now we will get all four rows back:
| department_name | employee_count |
|---|---|
| compliance | NULL |
| legal | 1 |
| it | 3 |
| finance | 5 |