PostgreSQL cardinality() Function

The PostgreSQL cardinality() function returns the total number of all elements in an array.

cardinality() Syntax

Here is the syntax of the PostgreSQL cardinality() function:

cardinality(array) -> integer

Parameters

array

Required. The array.

Return value

The PostgreSQL cardinality() function returns an integer that is the total number of elements in the specified array.

cardinality() Examples

One-dimensional Arrays

This example shows how to use a PostgreSQL cardinality() function to return the number of elements of a one-dimensional array.

SELECT cardinality(ARRAY[0, 1, 2]);
 cardinality
-------------
           3

This means that there are 3 elements in the array [0, 1, 2].

SELECT cardinality('[3:7]={1,1,1,1,1}'::integer[]);
 cardinality
-------------
           5

This means that there are 5 elements in the array [3:7]={1,1,1,1,1}.

Multidimensional Arrays

You can also get the total number of elements in a multidimensional array, for example:

SELECT cardinality('[2:4][2:3]={{1,1},{1,1},{1,1}}'::integer[]);
 cardinality
-------------
           6

This means that there are elements in the array [2:4][2:3]={{1,1},{1,1},{1,1}}.