How to find the size of an array in postgresql

aabi picture aabi · Jun 25, 2012 · Viewed 82.9k times · Source

Is there any way to find a size of an array?

For Example,

CREATE TABLE example (id integer[]) ;

INSERT INTO exam VALUES ( '{}');

INSERT INTO exam VALUES ( '{5,6,7}');

From this, is there any possibilities to get a result like following,

size

0

3

Answer

Adam Dingle picture Adam Dingle · May 9, 2015

As vyegorov mentioned, array_length will do the trick. Or if you know that the array is 1-dimensional (which is likely) and are running PostgreSQL 9.4 or higher, you can use cardinality:

SELECT cardinality(id) FROM example;