pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
How to count elements in an array?
2+ messages / 2 participants
[nested] [flat]

* How to count elements in an array?
@ 2001-03-05 22:49  Grant <grant@conprojan.com.au>
  0 siblings, 1 reply; 2+ messages in thread

From: Grant @ 2001-03-05 22:49 UTC (permalink / raw)
  To: pgsql-sql

How can I obtain a count (number) of elements in a text array? Thanks.

test=# \d array
                              Table "array"
  Attribute   |  Type   |                    Modifier
--------------+---------+------------------------------------------------
 id           | integer | not null default nextval('array_id_seq'::text)
 to_group_ids | text[]  |
Index: array_pkey

test=#

--- EXAMPLE SELECT ---

test=# select to_group_ids[1] from array where id=1;
 to_group_ids
--------------
 1
(1 row)

test=#




^ permalink  raw  reply  [nested|flat] 2+ messages in thread

* Re: How to count elements in an array?
@ 2001-03-06 04:52  Josh Berkus <josh@agliodbs.com>
  parent: Grant <grant@conprojan.com.au>
  0 siblings, 0 replies; 2+ messages in thread

From: Josh Berkus @ 2001-03-06 04:52 UTC (permalink / raw)
  To: Grant <grant@conprojan.com.au>; pgsql-sql

Grant,

	The only way I know to enumarate arrays is procedural.  This is a good
reason to stay away from arrays except in buffer and temporary tables
(aside from the fact that array columns violate the relational principle
of atomicity).

	The following sample procedure, paraphrased from Bruce Momjian's book
(which you should buy, hint, hint) illustrates enumerating an array of
INT4 values:

CREATE FUNCTION count_array ( INT4[] ) RETURNS INT2
AS '
DECLARE 
	array_loop INT2;
	array_col ALIAS FOR $1;
BEGIN
	array_loop := 1;
	WHILE array_col[array_loop]  LOOP
		array_loop = array_loop + 1;
	END LOOP;
	array_loop := array_loop - 1
	RETURN array_loop;
END;'
LANGUAGE 'plpgsql';


					-Josh
-- 
______AGLIO DATABASE SOLUTIONS___________________________
                                        Josh Berkus
   Complete information technology      josh@agliodbs.com
    and data management solutions       (415) 565-7293
   for law firms, small businesses       fax  621-2533
    and non-profit organizations.       San Francisco



^ permalink  raw  reply  [nested|flat] 2+ messages in thread


end of thread, other threads:[~2001-03-06 04:52 UTC | newest]

Thread overview: 2+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2001-03-05 22:49 How to count elements in an array? Grant <grant@conprojan.com.au>
2001-03-06 04:52 ` Josh Berkus <josh@agliodbs.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox