PostgreSQL 18 reference · Array Functions
PostgreSQL CARDINALITY() Function
Return the total number of elements in an array across all dimensions, and 0 for an empty array.
PostgreSQL 18 Since 9.4
Syntax
cardinality(array)
Parameters
| Parameter | Description |
|---|---|
array |
An array value. |
Return value
integer.
Examples
SELECT cardinality(ARRAY[[1, 2], [3, 4]]) AS elements;
Output
elements
----------
4
(1 row)Run this on your computer — see “Get Started” for setup.
SELECT country, cardinality(array_agg(name)) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC
LIMIT 2;
Output
country | customers ---------+----------- USA | 5 UK | 2 (2 rows)
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| PostgreSQL 9.4 | Added |
Related
ARRAY_LENGTH()· Return the length of one dimension of an array (use 1 for ordinary arrays). Empty arrays give NULL, not 0.JSONB_ARRAY_LENGTH()· Return the number of elements in a JSON array. Raises an error for objects and scalars.- SQL String Functions · tutorial