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?
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 .
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.
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.
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;
unnest --> expand an array to a set of rows
unnest(ARRAY[1,2]) 1 2
http://www.sqlfiddle.com/#!1/c774a/24
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With