Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unwrap postgresql array into rows

What is the fastest way to unwrap array into rows in PostgreSQL? For instance,

We have:

a - {1,2} {2,3,4} 

And we need:

b -  1 2 2 3 4 

I'm using:

select explode_array(a) as a from a_table; 

where explode_array is:

create or replace function explode_array(in_array anyarray) returns setof anyelement as $$     select ($1)[s] from generate_series(1,array_upper($1, 1)) as s; $$ 

Is there any better way?

like image 668
potapuff Avatar asked Sep 05 '11 14:09

potapuff


People also ask

How do I split an array into a row in SQL?

Converting elements in an array to rows in a table. To convert an ARRAY into a set of rows, also known as "flattening," use the UNNEST operator. UNNEST takes an ARRAY and returns a table with a single row for each element in the ARRAY .

What does the PostgreSQL Unnest () function do?

Unnest function generates a table structure of an array in PostgreSQL. Unnest array function is beneficial in PostgreSQL for expanding the array into the set of values or converting the array into the structure of the rows. PostgreSQL offers unnest() function.

What is Array_agg?

Summary. The ARRAY_AGG aggregator creates a new SQL. ARRAY value per group that will contain the values of group as its items. ARRAY_AGG is not preserving order of values inside a group. If an array needs to be ordered, a LINQ OrderBy can be used.


2 Answers

Use unnest. For example:

CREATE OR REPLACE FUNCTION test( p_test text[] )   RETURNS void AS $BODY$ BEGIN   SELECT id FROM unnest( p_test ) AS id; END; $BODY$   LANGUAGE plpgsql IMMUTABLE   COST 1; 
like image 167
Gavin Avatar answered Oct 12 '22 23:10

Gavin


unnest --> expand an array to a set of rows

unnest(ARRAY[1,2]) 1 2 

http://www.sqlfiddle.com/#!1/c774a/24

like image 25
Suraz Avatar answered Oct 13 '22 01:10

Suraz