Arrays and seriesSQL standard

CARDINALITY

Counts how many elements an array has.

Syntax

CARDINALITY(<array>)

Returns the total number of elements in an array, however many dimensions it has. For an empty array — 0. The similar ARRAY_LENGTH asks about the length of a specific dimension and gives NULL for an empty array. Handy for finding out how many tags or roles a row has, or for picking rows with a non-empty list.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

How many elements
SELECT CARDINALITY(ARRAY['sql', 'postgres', 'database']) AS tag_count;
tag_count
3
How many parts each phone number has
SELECT name, phone,
CARDINALITY(STRING_TO_ARRAY(phone, ' ')) AS parts
FROM employees;
namephoneparts
Emma+44 7700 9001233
LiamNULLNULL
Olivia+44 7700 9004563
Noah+44 7700 9007893
SophiaNULLNULL
A two-dimensional array
SELECT CARDINALITY(ARRAY[[1, 2], [3, 4]]) AS all_elements;
all_elements
4

CARDINALITY counts all the elements — 4, while ARRAY_LENGTH(…, 1) would give the number of rows — 2.

Watch out

To check whether an array is empty, write CARDINALITY(tags) = 0: with ARRAY_LENGTH this check doesn't work, because it gives NULL for an empty array.

NULL instead of an array gives NULL, not 0.

A NULL inside an array is an element too: CARDINALITY(ARRAY['a', NULL]) gives 2.