Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the size of an array in postgresql

People also ask

How do I find the size of an array in SQL?

Show activity on this post. 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.

How do you find the size of an array?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);

How do I find the length of a column in PostgreSQL?

The PostgreSQL length() function is used to find the length of a string i.e. number of characters in the given string. Example: PostgreSQL LENGTH() function: In the example below the length function returns the length of the given string 'w3resource'.


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;

It's trivial reading docs:

SELECT array_length(id, 1) FROM example;

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?


Had to use array_upper in postgres 8.2.