Sub topic 4
Inspecting arrays: cardinality, array_length, array_position
This chapter assumes you can write basic SELECT, INSERT and UPDATE statements. It also assumes you know how to declare an array column and write array values, and that you understand NULL and three-valued logic in SQL. You will learn to measure an array, locate an element in it, and predict what each function returns for empty arrays, NULL arrays, NULL elements and multidimensional arrays.
The sample data
The examples use the posts table from the earlier chapters, plus a third row that relies on the default empty array. If you are starting from scratch, run this setup:
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
INSERT INTO posts (title, tags) VALUES
('Intro to arrays', ARRAY['sql', 'postgres']),
('Indexing', '{postgres,indexing,gin}');
INSERT INTO posts (title) VALUES ('Draft');The table now has three rows. "Intro to arrays" has two tags, "Indexing" has three, and "Draft" has an empty array.
Two ways to ask "how big is this array?"
PostgreSQL has two common size functions, and they answer slightly different questions.
cardinality(arr)returns the total number of elements, counting across every dimension.array_length(arr, dim)returns the number of elements along one dimension that you name. The second argument is required.
For a one-dimensional array holding elements, the two agree:
SELECT title,
cardinality(tags) AS n,
array_length(tags, 1) AS len
FROM posts
ORDER BY id; title | n | len
-----------------+---+-----
Intro to arrays | 2 | 2
Indexing | 3 | 3
Draft | 0 |The "Draft" row shows the main difference. cardinality of an empty array is 0. array_length of an empty array is NULL, because an empty array has no dimensions, so there is no first dimension to measure.
Why array_length returns NULL for an empty array
In PostgreSQL, '{}' is an array with zero dimensions. It is not a one-dimensional array with zero elements. Every dimension-based function (array_length, array_lower, array_upper, array_ndims, array_dims) therefore returns NULL for it. cardinality was added to give an answer that matches intuition.
This causes a classic bug:
-- Misses empty arrays instead of treating them as length 0
SELECT title FROM posts WHERE array_length(tags, 1) < 1; -- returns no rows
-- Works
SELECT title FROM posts WHERE cardinality(tags) = 0; -- returns 'Draft'The first query returns nothing. For "Draft" the comparison is NULL < 1, which is NULL, and WHERE keeps only rows where the condition is true.
Edge cases at a glance
The function results shift with the shape of the input. This one-row query evaluates four inputs and prints the results of the size functions:
SELECT label,
cardinality(arr) AS cardinality,
array_length(arr, 1) AS length_dim1,
array_ndims(arr) AS ndims
FROM (VALUES
('empty', '{}'::int[]),
('null array', NULL::int[]),
('null element', '{1,NULL,3}'::int[]),
('2 x 3 matrix', '{{1,2,3},{4,5,6}}'::int[])
) AS t(label, arr);| Input | cardinality | array_length(arr, 1) | array_ndims |
|---|---|---|---|
| `'{}'` (empty) | 0 | NULL | NULL |
| `NULL` array | NULL | NULL | NULL |
| `'{1,NULL,3}'` | 3 | 3 | 1 |
| `'{{1,2,3},{4,5,6}}'` | 6 | 2 | 2 |
Three points follow from the table:
- A NULL array and an empty array are different values.
cardinalitytells them apart (NULL versus 0), andarray_lengthdoes not. - NULL elements count.
{1,NULL,3}has three elements, not two. - For multidimensional arrays,
cardinalitycounts every element (6), whilearray_length(arr, 1)counts only the outer dimension (2).
Handling a nullable array column
The posts.tags column is NOT NULL, so it never holds a NULL array. If your column allows NULLs, wrap the call so that "no tags" has one consistent meaning:
SELECT coalesce(cardinality(tags), 0) AS tag_count
FROM posts;Dimensions and bounds
Four more functions describe an array's shape. They matter mostly for multidimensional arrays, but you will meet them in error messages and psql output too.
SELECT array_ndims(a) AS ndims,
array_dims(a) AS dims,
array_lower(a, 1) AS lower_1,
array_upper(a, 1) AS upper_1,
array_length(a, 2) AS length_2,
array_length(a, 3) AS length_3
FROM (SELECT '{{1,2,3},{4,5,6}}'::int[] AS a) AS s; ndims | dims | lower_1 | upper_1 | length_2 | length_3
-------+------------+---------+---------+----------+----------
2 | [1:2][1:3] | 1 | 2 | 3 |array_ndimsreturns the number of dimensions.array_dimsreturns the bounds of every dimension as text, in[lower:upper]form.array_lowerandarray_upperreturn the first and last valid subscript for one dimension.- A dimension number that does not exist (here
3) returns NULL rather than raising an error.
Arrays that do not start at 1
Subscripts usually start at 1, but PostgreSQL allows other lower bounds. You can write one explicitly in a literal, and slice assignment on an array can also produce one. Then array_length equals upper - lower + 1, not the highest subscript:
SELECT array_lower(a, 1) AS lower_bound,
array_upper(a, 1) AS upper_bound,
array_length(a, 1) AS len,
array_position(a, 'b') AS pos_of_b
FROM (SELECT '[0:2]={a,b,c}'::text[] AS a) AS s; lower_bound | upper_bound | len | pos_of_b
-------------+-------------+-----+----------
0 | 2 | 3 | 1The array has three elements numbered 0 to 2. The element 'b' sits at subscript 1, and array_position reports the subscript, not a count from the start. Ordinary data created with ARRAY[...] or '{...}' always starts at 1, so this only matters if you build arrays with custom bounds.
Finding an element with array_position
array_position(arr, value) returns the subscript of the first element equal to value. If the value is not present, it returns NULL.
SELECT title,
array_position(tags, 'postgres') AS postgres_at
FROM posts
ORDER BY id; title | postgres_at
-----------------+-------------
Intro to arrays | 2
Indexing | 1
Draft |A NULL result means "absent", so you can use it as a presence test:
SELECT title
FROM posts
WHERE array_position(tags, 'gin') IS NOT NULL;This returns "Indexing". For plain membership tests, the operators in the later search chapter (@>, = ANY) are the normal choice, and unlike array_position they can use a GIN index. Reach for array_position when you need the position itself, such as ordering by how early a tag appears.
Starting the search later
An optional third argument sets the subscript where the search begins. This lets you find the second occurrence:
SELECT array_position(ARRAY['a','b','a','c'], 'a') AS first_a,
array_position(ARRAY['a','b','a','c'], 'a', 2) AS next_a; first_a | next_a
---------+--------
1 | 3Finding every position
array_positions(arr, value) returns an integer[] of all matching subscripts:
SELECT array_positions(ARRAY['a','b','a','c'], 'a') AS all_a,
array_positions(ARRAY['a','b','a','c'], 'z') AS no_z; all_a | no_z
-------+------
{1,3} | {}When nothing matches, array_positions returns an empty array, not NULL. This differs from array_position, so check which function you are calling before you write an IS NULL test.
NULL values and array_position
array_position compares with IS NOT DISTINCT FROM semantics, not =. This means it can find a NULL element, which a plain = comparison would never match:
SELECT array_position(ARRAY['x', NULL, 'y'], NULL) AS null_at,
array_position(ARRAY['x', 'y'], NULL) AS no_null; null_at | no_null
---------+---------
2 |If the array itself is NULL, the result is NULL as well. In no_null, the NULL result means "not found", and in a NULL array it would mean "no array". The function does not let you distinguish those two cases, so check the array separately if that matters.
Type and dimension limits
- The searched value must be compatible with the element type.
array_position(tags, 'postgres')works because the unknown-typed literal resolves totext.array_position(ARRAY[1,2,3], 'one')fails with an invalid input syntax error for integer, because the literal is read as an integer. array_positionandarray_positionsonly accept one-dimensional arrays. A multidimensional array raises an error saying that searching for elements in multidimensional arrays is not supported.
Choosing the right function
Putting the functions together
A realistic use is reporting on tag usage per post while handling empty arrays correctly:
SELECT id,
title,
cardinality(tags) AS tag_count,
CASE
WHEN cardinality(tags) = 0 THEN 'untagged'
WHEN array_position(tags, 'postgres') = 1 THEN 'postgres-first'
WHEN array_position(tags, 'postgres') IS NOT NULL THEN 'postgres-related'
ELSE 'other'
END AS category
FROM posts
ORDER BY id; id | title | tag_count | category
----+-----------------+-----------+------------------
1 | Intro to arrays | 2 | postgres-related
2 | Indexing | 3 | postgres-first
3 | Draft | 0 | untaggedThe CASE checks emptiness first. This keeps each later branch simple, because array_position on an empty array would only return NULL anyway.
Common mistakes
- Using
array_length(arr, 1) = 0to find empty arrays. It never matches; usecardinality(arr) = 0. - Forgetting the dimension argument.
array_length(tags)does not exist and raises a "function does not exist" error. - Treating a NULL from
array_positionas an error. It means "not found". - Expecting
cardinalityto equalarray_length(arr, 1)for matrices. It counts all elements, so for a 2 x 3 array it returns 6. - Using
array_positionas a row filter on a large table and expecting an index to help. Only the containment and overlap operators can use a GIN index.
Exercise
Write a query that returns the title and tag count for every post that has no tags at all, and explain why WHERE array_length(tags, 1) = 0 would not work. With the sample data, which row should come back?
Show answer
Use SELECT title, cardinality(tags) AS tag_count FROM posts WHERE cardinality(tags) = 0;. It returns the "Draft" row with a tag count of 0. array_length(tags, 1) returns NULL for an empty array, because '{}' has zero dimensions, so the condition becomes NULL = 0. That evaluates to NULL, which WHERE treats as not true, and no rows come back.
Exercise
Given ARRAY['red','green','red','blue','red'], write one query that returns the position of the first 'red', the position of the next 'red' after that one, and the array of all positions of 'red'. What does each column contain?
Show answer
Query: SELECT array_position(a, 'red') AS first_red, array_position(a, 'red', 2) AS next_red, array_positions(a, 'red') AS all_red FROM (SELECT ARRAY['red','green','red','blue','red'] AS a) AS s;. The results are first_red = 1, next_red = 3 and all_red = {1,3,5}. The third argument of array_position is the subscript where the search starts, so starting at 2 skips the first element and finds the red at position 3.