Sub topic 6
NULL elements and empty arrays
An array column can hold a missing value in three ways. The whole array can be NULL, the array can be empty, or the array can contain NULL elements. PostgreSQL treats these three cases differently. Mixing them up produces rows that silently vanish from query results. This chapter shows how each case behaves and how to guard against the surprises.
It assumes you can write SELECT, INSERT, UPDATE and WHERE clauses, and that you know three-valued logic (a comparison with NULL gives NULL, not false). It also assumes you know the ARRAY[...] constructor, '{...}' literals, and the @>, &&, ANY and ALL operators from earlier chapters.
Four states of an array value
Take a text[] column. A given row can be in any of these states:
| State | Example literal | Meaning |
|---|---|---|
| NULL array | `NULL::text[]` | The value is unknown or not set |
| Empty array | `'{}'::text[]` | Known to have zero elements |
| Array with a NULL element | `ARRAY['sql', NULL]` | Two slots, one of them unknown |
| Ordinary array | `ARRAY['sql', 'postgres']` | Two known elements |
Setting up sample data
The script below builds a temporary table with one row in each state. The column is deliberately nullable, so the NULL-array case is possible.
CREATE TEMP TABLE posts_nulls (
id int PRIMARY KEY,
title text NOT NULL,
tags text[]
);
INSERT INTO posts_nulls (id, title, tags) VALUES
(1, 'Intro', ARRAY['sql', 'postgres']),
(2, 'Untagged', '{}'),
(3, 'Unknown', NULL),
(4, 'Partial', ARRAY['sql', NULL]);Row 2 says "this post has no tags". Row 3 says "we don't know the tags". Row 4 has one real tag and one unknown slot.
Empty arrays: cardinality versus array_length
An empty array has no dimensions at all. array_length(arr, 1) asks for the length of dimension 1, and an empty array has no such dimension, so the result is NULL, not 0. cardinality counts the total number of elements and returns 0.
SELECT
array_length('{}'::text[], 1) AS len_empty,
cardinality('{}'::text[]) AS card_empty,
cardinality(NULL::text[]) AS card_null,
cardinality(ARRAY[NULL]::text[]) AS card_one_null,
array_length(ARRAY[NULL]::text[], 1) AS len_one_null,
array_ndims('{}'::text[]) AS ndims_empty;The result is:
| len_empty | card_empty | card_null | card_one_null | len_one_null | ndims_empty |
|---|---|---|---|---|---|
| NULL | 0 | NULL | 1 | 1 | NULL |
An array holding a single NULL element has length 1. It is not empty. array_dims, array_upper and array_lower also return NULL for an empty array.
Apply this to the sample table:
SELECT title,
tags IS NULL AS is_null_array,
cardinality(tags) AS card,
array_length(tags, 1) AS len
FROM posts_nulls
ORDER BY id;| title | is_null_array | card | len |
|---|---|---|---|
| Intro | false | 2 | 2 |
| Untagged | false | 0 | NULL |
| Unknown | true | NULL | NULL |
| Partial | false | 2 | 2 |
Consider the filter WHERE array_length(tags, 1) > 0. Row 2 gives NULL > 0, which is NULL, so the row is dropped. That is the right outcome for "has at least one tag". It becomes a bug in the negated form WHERE NOT (array_length(tags, 1) > 0), which also drops row 2 when you meant to find untagged posts.
Writing empty arrays correctly
There are two ways to write a typed empty array:
SELECT '{}'::text[] AS from_literal,
ARRAY[]::text[] AS from_constructor,
ARRAY(SELECT 'x' WHERE false) AS from_subquery;All three give {}. The bare expression ARRAY[] fails with "cannot determine type of empty array", because PostgreSQL has no elements to infer the type from. Add the cast: ARRAY[]::text[].
In a column definition, DEFAULT '{}' plus NOT NULL removes the NULL-array state and leaves only empty or populated. That is usually the simplest convention for application tables.
NULL elements in literals
In the '{...}' syntax, an unquoted NULL (case-insensitive) is a NULL element. A quoted "NULL" is the four-letter string.
SELECT '{a,NULL,c}'::text[] AS null_element,
'{a,"NULL",c}'::text[] AS string_null,
'{a,null,c}'::text[] AS lowercase_null;The first and third values contain a NULL in the middle. The second contains the text NULL, which PostgreSQL prints with quotes: {a,"NULL",c}. Mistaking one for the other is a common data-import bug.
Comparisons: ANY, ALL and three-valued logic
x = ANY (arr) is true if any element equals x. It is false if no element equals x and no element is NULL. It is NULL if no element equals x and at least one element is NULL, because the comparison with that NULL is unknown.
SELECT
1 = ANY (ARRAY[1, NULL]) AS found_with_null, -- true
1 = ANY (ARRAY[2, NULL]) AS missing_with_null, -- NULL
1 = ANY (ARRAY[2, 3]) AS missing_clean, -- false
1 = ANY ('{}'::int[]) AS any_on_empty, -- false
1 = ALL ('{}'::int[]) AS all_on_empty, -- true
1 <> ALL (ARRAY[2, NULL]) AS notall_with_null; -- NULLTwo rules follow from this:
ANYover an empty array is false, andALLover an empty array is true. The condition "for every element" holds trivially when there are no elements.- A NULL element can turn a definite "no" into "unknown". Inside WHERE, unknown rows are discarded.
Here is how that plays out on the sample table. The first query returns the untagged post. The second does not.
SELECT title FROM posts_nulls WHERE NOT ('gin' = ANY (tags));
SELECT title FROM posts_nulls WHERE NOT (tags @> ARRAY['gin']);For the first query, the per-row values of 'gin' = ANY (tags) are false for Intro and Untagged, NULL for Unknown (NULL array) and NULL for Partial (it has a NULL element and no match). After NOT, only Intro and Untagged remain.
The second query uses containment. @> compares elements with equality but never returns NULL because of a NULL element. It simply fails to match, so the result is false for Partial. Only a NULL array (Unknown) gives NULL. The result is Intro, Untagged and Partial.
The two queries answer "does this post lack the tag gin?" and return different sets. If posts with unknown tags should count as lacking the tag, say so explicitly:
SELECT title
FROM posts_nulls
WHERE tags IS NULL
OR NOT (tags @> ARRAY['gin']);Operators with empty arrays and NULL elements
Containment and overlap treat the empty array by set logic:
| Expression | Result | Reason |
|---|---|---|
| `ARRAY[1,2] @> '{}'::int[]` | true | Every array contains the empty set |
| `'{}'::int[] @> ARRAY[1]` | false | The empty array contains nothing |
| `ARRAY[1,2] && '{}'::int[]` | false | No shared element exists |
| `ARRAY[1,NULL] @> ARRAY[NULL]::int[]` | false | NULL never equals NULL in element matching |
| `ARRAY[NULL]::int[] && ARRAY[NULL]::int[]` | false | Same reason |
| `ARRAY[1,NULL] = ARRAY[1,NULL]` | true | Whole-array `=` treats NULLs as equal |
The last row is the exception. Whole-array comparison with =, < and > follows the same ordering rules that a B-tree index uses, which needs a total order, so NULL elements compare as equal to each other. Element-wise search operators do not.
Finding and removing NULL elements
array_position and array_positions find NULL elements, because they use "is not distinct from" comparison. array_remove works the same way, so it can strip NULLs.
SELECT
array_position(ARRAY['a', NULL, 'c'], NULL::text) AS first_null_at,
array_positions(ARRAY['a', NULL, NULL], NULL::text) AS all_null_positions,
array_remove(ARRAY['a', NULL, 'c'], NULL::text) AS cleaned;The result is 2, {2,3} and {a,c}.
You can use this to enforce a no-NULL-elements rule, since array_position returns NULL when nothing is found:
ALTER TABLE posts_nulls
ADD CONSTRAINT tags_no_null_elements
CHECK (array_position(tags, NULL::text) IS NULL);The constraint would reject row 4 as written, so run it only after cleaning the data:
UPDATE posts_nulls
SET tags = array_remove(tags, NULL::text)
WHERE array_position(tags, NULL::text) IS NOT NULL;A NOT NULL constraint on the column protects against a NULL array only. It does not stop ARRAY['x', NULL].
Modifying arrays that might be NULL
Append and concatenation functions treat a NULL array as an empty one, so you don't need a coalesce first:
SELECT array_append(NULL::text[], 'a') AS append_to_null,
array_cat(NULL::text[], ARRAY['a', 'b']) AS cat_with_null,
array_append(ARRAY['a'], NULL::text) AS append_null_element;The results are {a}, {a,b} and {a,NULL}. The last shows how NULL elements enter data by accident. If an application passes a missing value as a parameter, array_append(tags, $1) stores a NULL element and does not skip the update. Guard it in the statement:
UPDATE posts_nulls
SET tags = array_append(tags, 'tutorial')
WHERE id = 3
AND NOT coalesce(tags @> ARRAY['tutorial'], false);The coalesce is needed because row 3 has a NULL array. Without it, NOT (NULL) is NULL and the update would match no rows, so the NULL-array row would never get its first tag.
Empty results when converting between arrays and rows
The functions that convert between arrays and rows are asymmetric about empty input.
unnest of an empty array or a NULL array returns zero rows. A NULL element becomes a row containing NULL. A CROSS JOIN LATERAL unnest(...) therefore drops posts without tags. Use a left join to keep them:
SELECT p.title, t.tag
FROM posts_nulls AS p
LEFT JOIN LATERAL unnest(p.tags) AS t(tag) ON true
ORDER BY p.id;The output has rows (Intro, sql), (Intro, postgres), (Untagged, NULL), (Unknown, NULL), (Partial, sql) and (Partial, NULL). The NULL tag in rows 2 and 3 comes from the outer join, and the one in row 4 is a real NULL element. They look the same, so the output cannot tell them apart.
Going the other way, array_agg over zero input rows returns NULL, not an empty array. The ARRAY(subquery) form returns {}:
SELECT (SELECT array_agg(x) FROM unnest('{}'::int[]) AS x) AS agg_result,
ARRAY(SELECT x FROM unnest('{}'::int[]) AS x) AS subquery_result;The first is NULL and the second is {}. array_agg also keeps NULL inputs as NULL elements. To exclude them, add FILTER (WHERE x IS NOT NULL), which returns NULL again if nothing is left. Wrap it as coalesce(array_agg(x) FILTER (WHERE x IS NOT NULL), '{}') when you need an empty array.
Related display functions skip NULLs by default. array_to_string(ARRAY['a', NULL, 'c'], ',') returns a,c. Pass a third argument to show them: array_to_string(ARRAY['a', NULL, 'c'], ',', '*') returns a,*,c.
Summary of defensive habits
- Declare array columns
NOT NULL DEFAULT '{}'unless "unknown" is a meaningful state. - Use
cardinality, wrapped incoalescewhen the column is nullable, instead ofarray_length. - Prefer
@>to= ANYfor negated searches, and handle NULL arrays explicitly. - Reject NULL elements with a CHECK constraint when they carry no meaning.
- Use
LEFT JOIN LATERAL ... ON truewhen unnesting if empty arrays must stay visible. - Wrap
array_aggincoalesceor useARRAY(subquery)when callers expect an array.
Exercise
A table has tags text[] with rows {a}, {}, NULL and {a,NULL}. For the search tag b, which rows does WHERE NOT ('b' = ANY (tags)) return, and which does WHERE NOT (tags @> ARRAY['b']) return?
Show answer
The first query returns {a} and {}. For {a,NULL} the ANY test is NULL because no element equals b and one element is NULL, and NOT NULL is NULL, so the row is dropped. The NULL array is dropped too. The second query returns {a}, {} and {a,NULL}, because @> returns false (not NULL) when the NULL element fails to match. Only the NULL array is dropped.
Exercise
You need one array of tags per post, where posts with no tags show {} and NULL elements are removed. You write SELECT p.id, array_agg(t.tag) FROM posts_nulls p LEFT JOIN LATERAL unnest(p.tags) AS t(tag) ON true GROUP BY p.id. What is wrong with the result for the Untagged post, and how do you fix the query?
Show answer
The outer join produces one row with a NULL tag, so array_agg returns {NULL} (an array with a NULL element) instead of {}. Filter the NULLs out and substitute an empty array: coalesce(array_agg(t.tag) FILTER (WHERE t.tag IS NOT NULL), '{}'). Alternatively skip the join and use ARRAY(SELECT x FROM unnest(p.tags) AS x WHERE x IS NOT NULL), which returns {} when nothing remains.