Sub topic 4
Inspecting arrays: cardinality, array_length, array_position
This chapter assumes you know basic SELECT, WHERE, table creation, and PostgreSQL array syntax. It also assumes you understand that SQL comparisons involving NULL use three-valued logic.
PostgreSQL provides several functions for examining an array without expanding it into separate rows:
cardinality(array)counts all elements.array_length(array, dimension)returns the length of one dimension.array_position(array, value)returns the position of the first matching value.
These functions answer different questions. Choosing the right one matters, especially for empty arrays and multidimensional arrays.
Create sample data
The following temporary table exists only for the current database session. It includes a normal array, an empty array, a NULL array, and an array containing a NULL element.
CREATE TEMP TABLE inventory (
item text PRIMARY KEY,
quantities integer[]
);
INSERT INTO inventory (item, quantities) VALUES
('notebooks', ARRAY[12, 8, 4]),
('pens', ARRAY[]::integer[]),
('folders', NULL),
('markers', ARRAY[5, NULL, 5, 2]);An empty array has a value but contains no elements. A NULL array means that the array value itself is unknown or missing. These states are different.
Count elements with cardinality
Use cardinality when you want the total number of elements in an array.
SELECT item,
cardinality(quantities) AS element_count
FROM inventory
ORDER BY item;The result is conceptually:
| item | element_count |
|---|---|
| folders | NULL |
| markers | 4 |
| notebooks | 3 |
| pens | 0 |
cardinality returns NULL when its array argument is NULL. It returns 0 for an empty array. For a multidimensional array, it counts elements across all dimensions.
This makes cardinality useful for questions such as “Does this row contain any values?”
SELECT item
FROM inventory
WHERE cardinality(quantities) > 0;The condition excludes both empty arrays and NULL arrays. If you need to distinguish them, test separately.
Measure one dimension with array_length
array_length takes two arguments: the array and a dimension number. PostgreSQL uses one-based dimension numbers.
SELECT item,
array_length(quantities, 1) AS first_dimension_length
FROM inventory
ORDER BY item;For the one-dimensional arrays above, dimension 1 is the only dimension. However, array_length behaves differently from cardinality for an empty array: it returns NULL, not 0.
| Expression | Result |
|---|---|
| `cardinality('{}'::integer[])` | 0 |
| `array_length('{}'::integer[], 1)` | NULL |
| `cardinality(NULL::integer[])` | NULL |
| `array_length(NULL::integer[], 1)` | NULL |
This difference is important when writing conditions. Use cardinality(array) = 0 to find empty arrays. Do not use array_length(array, 1) = 0, because that comparison is never true for an empty array.
SELECT item
FROM inventory
WHERE cardinality(quantities) = 0;For a two-dimensional array, you can inspect each dimension separately.
SELECT array_length(ARRAY[
ARRAY[10, 20, 30],
ARRAY[40, 50, 60]
], 1) AS rows,
array_length(ARRAY[
ARRAY[10, 20, 30],
ARRAY[40, 50, 60]
], 2) AS columns;Both results are 2 and 3. The array has two rows and three columns, so cardinality would return 6.
Find a value with array_position
array_position returns the one-based position of the first matching element.
SELECT item,
array_position(quantities, 5) AS first_five
FROM inventory
ORDER BY item;For markers, the result is 1, because the first 5 occurs at position 1. For notebooks, pens, and folders, the result is NULL because no matching 5 is found, or the array itself is NULL.
You can use the function in a filter:
SELECT item
FROM inventory
WHERE array_position(quantities, 5) IS NOT NULL;Use IS NOT NULL, not = TRUE. array_position returns an integer position rather than a Boolean.
PostgreSQL compares array elements using IS NOT DISTINCT FROM. Therefore, you can search for a NULL element:
SELECT array_position(ARRAY[5, NULL, 5], NULL) AS null_position;The result is 2. This differs from an ordinary comparison such as NULL = NULL, whose result is NULL.
Exercise
What do these expressions return: cardinality(ARRAY[]::text[]), arraylength(ARRAY[]::text[], 1), and arrayposition(ARRAY['a', 'b', 'a'], 'a')?
Show answer
They return 0, NULL, and 1. The array is empty in the first two expressions, and array_position returns the first one-based position of 'a'.