Sub topic 2
How NULL behaves in string expressions
This chapter assumes you can write basic SELECT, WHERE and GROUP BY queries, know the common PostgreSQL data types, and can run queries in psql or another SQL client. It covers how NULL propagates through string operators and functions, which functions are exceptions, and how to convert between NULL and the empty string on purpose.
NULL is not an empty string
NULL means "no known value". The empty string '' is a known value that happens to contain zero characters. PostgreSQL treats them as different things:
'' IS NULLis false.char_length('')is0.char_length(NULL)is NULL.
Oracle treats '' as NULL, so code ported from Oracle often breaks on this point. PostgreSQL follows the SQL standard.
By default psql prints NULL as nothing, so a NULL and an empty string look identical in output. Make them distinguishable while you experiment:
\pset null '(null)'
SELECT NULL::text AS a_null, ''::text AS an_empty_string;The propagation rule
Most string functions and operators are strict. If any input is NULL, the result is NULL, and the function body never runs. This holds for upper, lower, substring, replace, lpad, trim, char_length, strpos and many others. It also holds for the || operator and for comparisons.
| Expression | Result | Column | Column |
|---|---|---|---|
| `'a' \ | \ | NULL` | NULL |
| `upper(NULL)` | NULL | ||
| `char_length(NULL)` | NULL | ||
| `replace('a-b', '-', NULL)` | NULL | ||
| `'abc' = NULL` | NULL | ||
| `'abc' LIKE NULL` | NULL |
The last two rows matter most in practice. A comparison with NULL produces NULL, not false. WHERE keeps only rows where the condition is true, so rows where it is NULL are dropped silently.
-- Returns no rows, even if some rows have a NULL nickname.
SELECT * FROM people WHERE nickname = NULL;
-- Correct test:
SELECT * FROM people WHERE nickname IS NULL;Negation does not rescue you. NOT (NULL) is still NULL, so WHERE nickname NOT LIKE 'A%' also drops rows whose nickname is NULL. If you want those rows, say so explicitly:
SELECT *
FROM people
WHERE nickname NOT LIKE 'A%' OR nickname IS NULL;Concatenation: three behaviors
The three concatenation tools handle NULL differently. This is the example from the plan for this tutorial:
SELECT 'a' || NULL AS with_operator,
concat('a', NULL, 'b') AS with_concat,
concat_ws(', ', 'x', NULL, 'z') AS with_separator;The result is NULL, ab and x, z.
||is strict. One NULL operand makes the whole result NULL.concatignores NULL arguments. It treats them as if they were not there.concat_ws(separator, ...)also ignores NULL arguments, and it adds no separator for them. That is why you getx, zand notx, , z.
Two edge cases:
concat(NULL)andconcat_ws(',', NULL, NULL)return an empty string'', not NULL. A concatenation of nothing is still a string.concat_wsis strict in its first argument.concat_ws(NULL, 'a', 'b')returns NULL.
concat and concat_ws are not strict in general, so a NULL passed to them cannot make the result NULL, apart from the separator case above.
Worked example: building a full name
Create a small table with the cases that cause trouble:
CREATE TEMP TABLE people (
id int,
first_name text,
middle_name text,
last_name text
);
INSERT INTO people VALUES
(1, 'Ada', 'Byron', 'Lovelace'),
(2, 'Alan', NULL, 'Turing'),
(3, 'Grace', '', 'Hopper'),
(4, 'Linus', NULL, NULL);
SELECT id,
first_name || ' ' || middle_name || ' ' || last_name AS by_operator,
concat_ws(' ', first_name, middle_name, last_name) AS by_concat_ws
FROM people
ORDER BY id;With \pset null '(null)' the output is:
| id | by_operator | by_concat_ws |
|---|---|---|
| 1 | Ada Byron Lovelace | Ada Byron Lovelace |
| 2 | (null) | Alan Turing |
| 3 | Grace Hopper | Grace Hopper |
| 4 | (null) | Linus |
Row 2 shows the operator losing the whole name because of one missing middle name. Row 3 shows a second problem. The empty string is a real value, so concat_ws keeps it and writes two separators, giving Grace Hopper with a double space. concat_ws only skips NULL, never ''.
The fix is to turn empty strings into NULL first with nullif:
SELECT id,
concat_ws(' ', first_name, nullif(trim(middle_name), ''), last_name) AS full_name
FROM people
ORDER BY id;nullif(a, b) returns NULL when a = b and a otherwise. Wrapping trim inside also catches values that contain only spaces. Row 3 now gives Grace Hopper.
Converting between NULL and a default
coalesce(a, b, ...) returns the first argument that is not NULL. It is the standard way to supply a replacement for a missing value so a strict operator keeps working:
SELECT id,
first_name || ' ' || coalesce(middle_name, '') || ' ' || last_name AS padded_name
FROM people
WHERE id IN (1, 2);This avoids the NULL, but row 2 now reads Alan Turing with two spaces. For optional pieces, concat_ws with nullif is usually cleaner than coalesce plus ||, because it also handles the separators.
coalesce and nullif are opposites. Use coalesce to replace NULL with a value, and nullif to replace a specific value (often '') with NULL. Many cleaning pipelines use both: coalesce(nullif(trim(col), ''), 'unknown').
Comparing with NULL safely
To compare two values where either may be NULL, use IS DISTINCT FROM and IS NOT DISTINCT FROM. They treat NULL as a comparable value and always return true or false:
SELECT 'a' IS DISTINCT FROM NULL AS differs, -- true
NULL IS DISTINCT FROM NULL AS both_null, -- false
NULL IS NOT DISTINCT FROM NULL AS same; -- trueA common use is finding changed values between two versions of a row, where old.name <> new.name would miss a change from a value to NULL.
Aggregates and arrays
Aggregation functions also skip NULL, with one edge case. string_agg(value, delimiter) ignores rows where value is NULL. If every input is NULL, or there are no rows, the result is NULL and not ''.
SELECT string_agg(middle_name, ', ' ORDER BY id) AS middles
FROM people;This returns Byron, followed by nothing visible for the empty string, so the output is Byron, . The NULL rows were skipped, but the row with '' contributed an empty item. Wrap the column in nullif(middle_name, '') if you do not want that.
array_to_string(array, delimiter [, null_string]) skips NULL elements unless you pass the third argument, which supplies the text to print in their place:
SELECT array_to_string(ARRAY['a', NULL, 'c'], '-') AS skipped, -- a-c
array_to_string(ARRAY['a', NULL, 'c'], '-', '?') AS substituted; -- a-?-cNULL inside format
The format function, covered later in this tutorial, has its own rules:
%sprints NULL as an empty string.%Lprints NULL as the unquoted wordNULL, which is what you want when building anINSERTstatement as text.%Iraises an error, because an identifier cannot be NULL.
SELECT format('value=%s', NULL::text) AS plain, -- value=
format('value=%L', NULL::text) AS literal; -- value=NULLDecision flow
Common errors
- Using
= NULL. It is never true. UseIS NULL. - Chaining
||over nullable columns. One NULL wipes out the whole result. Useconcat_wsorcoalesce. - Expecting
concat_wsto skip''. It skips only NULL. Usenulliffor empty or blank strings. - Forgetting that
NOT LIKEdrops NULL rows. AddOR col IS NULLwhen you want them. - Reading blank
psqloutput as an empty string. Set\pset nullto see which one you have. - Assuming
string_aggreturns''for no input. It returns NULL, so wrap it incoalesce(..., '')if the caller needs text.
Exercise
A query returns no rows for SELECT * FROM people WHERE middle_name <> 'Byron';, even though Alan Turing's middle_name is NULL. Why is Alan missing, and how do you include him?
Show answer
NULL <> 'Byron' evaluates to NULL, not true, so WHERE discards the row. Use WHERE middle_name IS DISTINCT FROM 'Byron', which returns true for NULL, or add OR middle_name IS NULL.
Exercise
Write an expression that builds a display name from firstname, middlename and lastname, separated by single spaces, where a NULL, empty or whitespace-only middlename leaves no extra space. What does it return for the row (4, 'Linus', NULL, NULL)?
Show answer
concat_ws(' ', first_name, nullif(trim(middle_name), ''), last_name). For Linus it returns Linus, because concat_ws skips both NULL arguments and adds no separator for them.