191

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

For Example,

CREATE TABLE example (id integer[]) ;

INSERT INTO example VALUES ( '{}');

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

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

size
---
0
3
0

4 Answers 4

277

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;
Sign up to request clarification or add additional context in comments.

7 Comments

If anyone can mention the major difference in using array_length and cardinality that would be great
cardinality returns the number of all the elements in a single or multidimensional array. So select cardinality(ARRAY[[1,2], [3,4]]); would return 4, whereas select array_length(ARRAY[[1,2], [3,4]], 1) would return 2. If you're counting the first dimension, array_length is a safer bet.
This also works for an array saved in a field with text type, while function array_length(text[]) does not exist ;)
@ZiaUlRehmanMughal also array length of an empty array unexpectedly evaluates to null and not 0 whereas cardinality returns what you'd expect. No idea what they were thinking with that logic.
Important difference: when the array is empty (i.e. length is zero), cardinality(id) returns 0, but array_length(id,1) returns NULL. So for 1-dimensional arrays cardinality is almost always what you want.
|
125

It's trivial reading docs:

SELECT array_length(id, 1) FROM example;

4 Comments

Do you know what is the second parameter of the function array_length. Didn't find that info in docs.
@suzanshakya, the length of the requested array dimension
This will return null and 3 instead of 0 and 3 for the OPs example. Definitely should promote use of cardinality when accepting an answer as it's easier to use and less unexpected (I imagine 99.999% use of arrays are single dimensional)
24

Assuming the dimension of the array will always be 1 isn't something I feel comfortable with, so I went with the following:

SELECT coalesce(array_length(id, 1), 0) as size FROM example;

It's been... at least a decade, but we used to do a lot with coalesce and it was pretty handy. Maybe I'm reaching for it out of comfort?

1 Comment

cardinality(id) will also return 0, as the other answer mentions
8

Had to use array_upper in postgres 8.2.

1 Comment

Life saver. As almost all posts out there are using array_length() assuming people are on postgres 9+ ;(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.