Array Unnest

From PostgreSQL wiki

Revision as of 14:35, 27 October 2009 by Intgr (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Compatibility Snippets

Array Unnest

Works with PostgreSQL

<=8.3

Written in

SQL

Depends on

Nothing

by Scott Bailey 'Artacus'

PostgreSQL 8.4 includes a function for expanding an array into a set of rows. It is extremely helpful when working with arrays. Here is how to add it to 8.3 and below.

CREATE OR REPLACE FUNCTION unnest(anyarray)
  RETURNS SETOF anyelement AS
$BODY$
SELECT $1[i] FROM
    generate_series(array_lower($1,1),
                    array_upper($1,1)) i;
$BODY$
  LANGUAGE 'sql' IMMUTABLE
Personal tools