Sub topic 10
Handling NULL with IS NULL and IS NOT NULL
This chapter assumes you know that a table contains rows and columns, and that SELECT and WHERE retrieve and filter rows. Examples use an employees table with columns such as first_name, last_name, manager_id, and salary.
What NULL means
NULL represents a missing, unknown, or inapplicable value. It is not the same as:
- Zero, such as
0 - An empty string, such as
'' - The text value
'NULL'
For example, an employee with no assigned manager might have manager_id set to NULL. The database does not know a manager ID for that row.
A comparison with NULL cannot produce a normal true or false result. It produces UNKNOWN.
| Expression | Result |
|---|---|
| `salary = NULL` | `UNKNOWN` |
Because a WHERE clause keeps only rows for which its condition is TRUE, this query does not find employees without managers:
SELECT first_name, last_name
FROM employees
WHERE manager_id = NULL;Test for missing values
Use IS NULL to find missing values:
SELECT first_name, last_name
FROM employees
WHERE manager_id IS NULL;Use IS NOT NULL to find values that are present:
SELECT first_name, last_name, manager_id
FROM employees
WHERE manager_id IS NOT NULL;The IS operators are specifically designed for testing NULL. Do not put NULL in quotes. 'NULL' is ordinary text and matches only a column containing those four characters.
NULL in larger conditions
SQL uses three logical results: TRUE, FALSE, and UNKNOWN. This matters when a condition contains AND, OR, or NOT.
For example, an employee with a missing salary makes salary > 50000 unknown:
SELECT first_name, salary
FROM employees
WHERE salary > 50000
AND manager_id IS NOT NULL;The row is returned only if both parts are true. An unknown comparison does not satisfy the WHERE clause.
With OR, a true condition can still make the entire condition true:
SELECT first_name, department, salary
FROM employees
WHERE department = 'Sales'
OR salary > 50000;A row in Sales can match even when its salary is NULL, because the first condition is true. However, a row in another department with a NULL salary produces unknown for both comparisons and is excluded.
NULL and sorting
ORDER BY can place NULL values at either end of the result. The default depends on the database system and whether the sort is ascending or descending. Use an explicit option when your database supports it:
SELECT first_name, salary
FROM employees
ORDER BY salary ASC NULLS LAST;PostgreSQL supports NULLS FIRST and NULLS LAST. MySQL, SQLite, and other systems may use different syntax or defaults, so check the dialect when the position of missing values matters.
Exercise
Write a query that returns the first and last names of employees whose salary is present but whose manager is missing.
Show answer
SELECT firstname, lastname FROM employees WHERE salary IS NOT NULL AND manager_id IS NULL;