๐Ÿงน Handling NULLs

NULL is the source of more wrong query results than any other part of SQL. The query runs, nothing fails, and yet rows quietly go missing or totals come out off.

This tutorial explains how NULL behaves in comparisons, filters, arithmetic, aggregates, grouping and sorting, and how to handle it on purpose instead of by accident.


Sample Data

We use the same employees view as in the introduction. It has a few NULLs on purpose: Grace has no dept, Elena has no city, and Asha and Grace have no manager_id.

CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
  (1, 'Asha',  'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
  (2, 'Ben',   'Engineering', 82000, DATE'2020-07-01', 1,    'Pune'),
  (3, 'Chen',  'Sales',       60000, DATE'2021-01-10', 1,    'Mumbai'),
  (4, 'Divya', 'Sales',       65000, DATE'2018-11-23', 3,    'Mumbai'),
  (5, 'Elena', 'Marketing',   58000, DATE'2022-05-30', 1,    NULL),
  (6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2,    'Bengaluru'),
  (7, 'Grace', NULL,          45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)

We also use a small bonuses view, where some bonuses have not been decided yet:

CREATE OR REPLACE TEMP VIEW bonuses AS
SELECT * FROM VALUES
  ('Asha',  10000),
  ('Ben',   NULL),
  ('Chen',  2000),
  ('Divya', NULL)
AS bonuses(name, bonus)

1. What NULL Means

NULL means "unknown" or "missing". It is not zero, and it is not an empty string:

ValueMeaning
0We know the number, and it is zero
''We know the text, and it is empty
NULLWe do not know the value at all

Everything else in this tutorial follows from one idea: if a value is unknown, any question about it usually has an unknown answer too.


2. Comparisons with NULL: Three-Valued Logic

In most programming languages a condition is either true or false. In SQL there is a third outcome: NULL (unknown). Comparing anything with NULL using =, <>, > and so on gives NULL:

SELECT 1 = 1       AS one_eq_one,
       1 = NULL    AS one_eq_null,
       NULL = NULL AS null_eq_null,
       NULL <> 5   AS null_ne_five
+----------+-----------+------------+------------+
|one_eq_one|one_eq_null|null_eq_null|null_ne_five|
+----------+-----------+------------+------------+
|true      |NULL       |NULL        |NULL        |
+----------+-----------+------------+------------+

Even NULL = NULL is NULL. Two unknown values are not known to be equal.

AND, OR and NOT follow the same logic. The result is only definite when the known part already decides it:

SELECT true  AND NULL AS true_and_null,
       false AND NULL AS false_and_null,
       true  OR  NULL AS true_or_null,
       false OR  NULL AS false_or_null,
       NOT NULL       AS not_null
+-------------+--------------+------------+-------------+--------+
|true_and_null|false_and_null|true_or_null|false_or_null|not_null|
+-------------+--------------+------------+-------------+--------+
|NULL         |false         |true        |NULL         |NULL    |
+-------------+--------------+------------+-------------+--------+

false AND anything is false, and true OR anything is true, so those two are not NULL. Every other combination stays unknown.

Why this matters: WHERE keeps a row only when the condition is true. Rows where the condition is false or NULL are dropped.


3. = NULL vs IS NULL

Because city = NULL is never true, this query returns nothing, even though Elena's city is missing:

SELECT name, city
FROM employees
WHERE city = NULL
+----+----+
|name|city|
+----+----+
+----+----+

To test for missing values, use IS NULL and IS NOT NULL. These always return true or false, never NULL:

SELECT name, city
FROM employees
WHERE city IS NULL
+-----+----+
|name |city|
+-----+----+
|Elena|NULL|
+-----+----+

Common mistake: NULLs also disappear from "not equal" filters. You might expect WHERE city <> 'Mumbai' to return everyone outside Mumbai, including Elena. It does not:

SELECT name, city
FROM employees
WHERE city <> 'Mumbai'
ORDER BY emp_id
+-----+---------+
|name |city     |
+-----+---------+
|Asha |Bengaluru|
|Ben  |Pune     |
|Farid|Bengaluru|
|Grace|Delhi    |
+-----+---------+

Elena is missing because NULL <> 'Mumbai' is NULL. If you want her included, say so explicitly: WHERE city <> 'Mumbai' OR city IS NULL.


4. NULL in Arithmetic and Strings

Any arithmetic with a NULL gives NULL. The same goes for concat() and the || operator:

SELECT name,
       city,
       salary + NULL            AS salary_plus_null,
       concat(name, ' - ', city) AS with_concat,
       name || ' - ' || city     AS with_pipes,
       concat_ws(' - ', name, city) AS with_concat_ws
FROM employees
WHERE emp_id IN (4, 5)
ORDER BY emp_id
+-----+------+----------------+--------------+--------------+--------------+
|name |city  |salary_plus_null|with_concat   |with_pipes    |with_concat_ws|
+-----+------+----------------+--------------+--------------+--------------+
|Divya|Mumbai|NULL            |Divya - Mumbai|Divya - Mumbai|Divya - Mumbai|
|Elena|NULL  |NULL            |NULL          |NULL          |Elena         |
+-----+------+----------------+--------------+--------------+--------------+

For Elena, both concat() and || return NULL, so her name is lost too. concat_ws(separator, ...) ("concat with separator") skips NULL arguments, which is usually what you want when building labels or addresses.


5. Aggregates Skip NULLs

Aggregate functions such as COUNT(column), SUM, AVG, MIN and MAX ignore NULL values. COUNT(*) is the exception: it counts rows, whatever they contain.

SELECT COUNT(*)             AS all_rows,
       COUNT(city)          AS rows_with_city,
       COUNT(DISTINCT city) AS distinct_cities,
       COUNT(manager_id)    AS rows_with_manager
FROM employees
+--------+--------------+---------------+-----------------+
|all_rows|rows_with_city|distinct_cities|rows_with_manager|
+--------+--------------+---------------+-----------------+
|7       |6             |4              |5                |
+--------+--------------+---------------+-----------------+

There are 7 employees, but only 6 have a city and only 5 have a manager. COUNT(DISTINCT city) returns 4 (Bengaluru, Delhi, Mumbai, Pune): NULL is not counted as a city.

This matters most with AVG. Look at the bonuses:

SELECT SUM(bonus)              AS total_bonus,
       COUNT(bonus)            AS people_with_bonus,
       AVG(bonus)              AS avg_ignoring_nulls,
       AVG(COALESCE(bonus, 0)) AS avg_treating_null_as_zero
FROM bonuses
+-----------+-----------------+------------------+-------------------------+
|total_bonus|people_with_bonus|avg_ignoring_nulls|avg_treating_null_as_zero|
+-----------+-----------------+------------------+-------------------------+
|12000      |2                |6000.0            |3000.0                   |
+-----------+-----------------+------------------+-------------------------+

AVG(bonus) divides the total, 12,000, by the 2 known bonuses, giving 6,000. If a missing bonus really means "no bonus", you want to divide by all 4 people, which AVG(COALESCE(bonus, 0)) does. Neither answer is wrong; they answer different questions. Decide which one you mean.

Interview tip: "What is the difference between COUNT(*), COUNT(col) and COUNT(DISTINCT col)?" is a classic. COUNT(*) counts rows, COUNT(col) counts non-NULL values, and COUNT(DISTINCT col) counts different non-NULL values.

When every value is NULL, SUM, AVG, MIN and MAX return NULL, but COUNT returns 0:

SELECT SUM(bonus)   AS sum_bonus,
       COUNT(bonus) AS count_bonus
FROM bonuses
WHERE bonus IS NULL
+---------+-----------+
|sum_bonus|count_bonus|
+---------+-----------+
|NULL     |0          |
+---------+-----------+

6. The NOT IN Trap

IN and NOT IN are shortcuts for a chain of = comparisons, so NULL causes surprises here too. If the list contains a NULL, NOT IN returns no rows at all:

SELECT name
FROM employees
WHERE emp_id NOT IN (1, 2, NULL)
+----+
|name|
+----+
+----+

Why? For Chen, emp_id NOT IN (1, 2, NULL) means 3 <> 1 AND 3 <> 2 AND 3 <> NULL. The last part is NULL, so the whole condition is NULL, and the row is dropped. The same happens to every row.

This bites in real queries when the list comes from a subquery. Let us find employees who do not manage anyone:

SELECT name
FROM employees
WHERE emp_id NOT IN (SELECT manager_id FROM employees)
+----+
|name|
+----+
+----+

Zero rows, because manager_id contains NULLs (Asha and Grace have no manager). Filter the NULLs out of the subquery and the expected answer appears:

SELECT name
FROM employees
WHERE emp_id NOT IN (SELECT manager_id FROM employees WHERE manager_id IS NOT NULL)
ORDER BY emp_id
+-----+
|name |
+-----+
|Divya|
|Elena|
|Farid|
|Grace|
+-----+

Common mistake: Using NOT IN (subquery) on a column that can contain NULL. Either filter the NULLs out, or use NOT EXISTS, which does not have this problem. See Subqueries & CTEs.


7. Null-Safe Equality: <=> and IS DISTINCT FROM

Sometimes you want two NULLs to count as equal, for example when comparing an old and a new version of a table. Spark has a null-safe equality operator, <=>, which always returns true or false:

SELECT 1 = 1      AS eq_1_1,
       1 <=> 1    AS nse_1_1,
       1 <=> NULL AS nse_1_null,
       NULL <=> NULL AS nse_null_null,
       NULL IS NOT DISTINCT FROM NULL AS not_distinct,
       1 IS DISTINCT FROM NULL        AS distinct_1_null
+------+-------+----------+-------------+------------+---------------+
|eq_1_1|nse_1_1|nse_1_null|nse_null_null|not_distinct|distinct_1_null|
+------+-------+----------+-------------+------------+---------------+
|true  |true   |false     |true         |true        |true           |
+------+-------+----------+-------------+------------+---------------+
Expressiona and b both knownOne of them NULLBoth NULL
a = btrue / falseNULLNULL
a <=> btrue / falsefalsetrue
a IS NOT DISTINCT FROM bsame as <=>falsetrue
a IS DISTINCT FROM bopposite of <=>truefalse

IS [NOT] DISTINCT FROM is the SQL-standard spelling; <=> is Spark's shorter one. You will see <=> again in Joins, where it lets NULL keys match.


8. Replacing NULLs

To fill in a default, use COALESCE, which returns its first non-NULL argument. IFNULL and NVL are two-argument versions of the same thing:

SELECT name,
       COALESCE(dept, 'Unassigned') AS dept,
       IFNULL(city, 'Unknown')      AS city,
       NVL(manager_id, 0)           AS manager_id
FROM employees
WHERE dept IS NULL OR city IS NULL OR manager_id IS NULL
ORDER BY emp_id
+-----+-----------+---------+----------+
|name |dept       |city     |manager_id|
+-----+-----------+---------+----------+
|Asha |Engineering|Bengaluru|0         |
|Elena|Marketing  |Unknown  |1         |
|Grace|Unassigned |Delhi    |0         |
+-----+-----------+---------+----------+

Replace NULLs as late as possible, usually in the final SELECT. If you replace NULL with 0 early on, later steps can no longer tell "zero" from "unknown", and averages and counts change. The CASE WHEN tutorial covers NULLIF, NVL2 and conditional logic in more depth.


9. NULLs in GROUP BY and DISTINCT

Comparisons treat NULLs as "not equal", but grouping does the opposite: all NULLs go into one group. The same is true for DISTINCT:

SELECT dept, COUNT(*) AS headcount
FROM employees
GROUP BY dept
ORDER BY dept
+-----------+---------+
|dept       |headcount|
+-----------+---------+
|NULL       |1        |
|Engineering|3        |
|Marketing  |1        |
|Sales      |2        |
+-----------+---------+
SELECT DISTINCT city
FROM employees
ORDER BY city
+---------+
|city     |
+---------+
|NULL     |
|Bengaluru|
|Delhi    |
|Mumbai   |
|Pune     |
+---------+

Grace forms a NULL department group of her own, and the city list has one NULL entry. If you do not want that group, filter it out with WHERE dept IS NOT NULL, or label it with COALESCE(dept, 'Unassigned').


10. Sorting NULLs

In Spark, NULLs sort first in ascending order and last in descending order. You can override this with NULLS FIRST or NULLS LAST:

SELECT name, city
FROM employees
ORDER BY city ASC NULLS LAST, name
+-----+---------+
|name |city     |
+-----+---------+
|Asha |Bengaluru|
|Farid|Bengaluru|
|Grace|Delhi    |
|Chen |Mumbai   |
|Divya|Mumbai   |
|Ben  |Pune     |
|Elena|NULL     |
+-----+---------+

Without NULLS LAST, Elena would be the first row, just as the NULL group and the NULL city came first in section 9. Other databases have different defaults (PostgreSQL and Oracle put NULLs last in ascending order), so being explicit makes your query behave the same everywhere.


Try It in the Online Compiler

Copy this into the PySpark Online Compiler and see the NOT IN trap for yourself:

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Spark SQL NULLs").getOrCreate()

spark.sql("""
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
  (1, 'Asha',  'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
  (2, 'Ben',   'Engineering', 82000, DATE'2020-07-01', 1,    'Pune'),
  (3, 'Chen',  'Sales',       60000, DATE'2021-01-10', 1,    'Mumbai'),
  (4, 'Divya', 'Sales',       65000, DATE'2018-11-23', 3,    'Mumbai'),
  (5, 'Elena', 'Marketing',   58000, DATE'2022-05-30', 1,    NULL),
  (6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2,    'Bengaluru'),
  (7, 'Grace', NULL,          45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
""")

# Returns no rows: manager_id contains NULLs
spark.sql("""
SELECT name FROM employees
WHERE emp_id NOT IN (SELECT manager_id FROM employees)
""").show(truncate=False)

# Returns the employees who manage nobody
spark.sql("""
SELECT name FROM employees
WHERE emp_id NOT IN (SELECT manager_id FROM employees WHERE manager_id IS NOT NULL)
ORDER BY emp_id
""").show(truncate=False)

spark.sql("""
SELECT COUNT(*) AS all_rows, COUNT(city) AS rows_with_city
FROM employees
""").show(truncate=False)

Summary

  • NULL means unknown. Comparisons with NULL return NULL, and WHERE drops rows whose condition is NULL.
  • Use IS NULL / IS NOT NULL, never = NULL. Remember that <> filters also drop NULL rows.
  • Arithmetic, concat() and || with a NULL give NULL; concat_ws skips NULLs.
  • Aggregates skip NULLs, except COUNT(*). Be clear whether AVG should ignore NULLs or treat them as zero.
  • NOT IN returns nothing if its list contains a NULL. Filter the NULLs out or use NOT EXISTS.
  • <=> and IS NOT DISTINCT FROM treat two NULLs as equal.
  • GROUP BY and DISTINCT put all NULLs together. NULLs sort first ascending in Spark; use NULLS FIRST / NULLS LAST to be explicit.

Next, you will learn how to combine tables with joins, where NULL keys play an important role.