Re: How to count the number of items in an Array?

From: Andreas Kretschmer <akretschmer(at)spamfence(dot)net>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: How to count the number of items in an Array?
Date: 2010-02-21 08:38:29
Message-ID: 20100221083829.GA9280@tux
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Andre Lopes <lopes80andre(at)gmail(dot)com> wrote:

> Hi,
>
> I have googled, but I can't find how to count the number of items in an Array
> in Plpgsql.
>
> Someone can give me a clue on that?

Sure, you can use array_upper() - array_lower():

Zeit: 0,205 ms
test=*# select array_upper(array[1,2,3],1) - array_lower(array[1,2,3],1);
?column?
----------
2
(1 Zeile)

or:

test=*# select array_upper(array[1,2,3],1) - array_lower(array[1,2,3],1) + 1;
?column?
----------
3
(1 Zeile)

Or, if your array starts with the first element, simple:

test=*# select array_upper(array[1,2,3,NULL,5],1);
array_upper
-------------
5
(1 Zeile)

Andreas
--
Really, I'm not out to destroy Microsoft. That will just be a completely
unintentional side effect. (Linus Torvalds)
"If I was god, I would recompile penguin with --enable-fly." (unknown)
Kaufbach, Saxony, Germany, Europe. N 51.05082°, E 13.56889°

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Andre Lopes 2010-02-21 14:05:24 Re: How to count the number of items in an Array?
Previous Message Pavel Stehule 2010-02-21 07:38:22 Re: Asynchronous queries - processing listen (notify) in a procedural language