Skip to content

UNNEST

  • anyarray: UNNEST(anyarray) takes as parameter an array. This parameter represents the array that will be disassembled into a set of rows.
  • returns setof anyelement: This is the syntax specifying the type of return value from the UNNEST() function. It indicates that the function will return a set of elements whose datatype is the same as the datatype of the elements of the array parameter. The number of rows returned corresponds to the number of elements in the array.
CREATE TABLE temp_table (numbers INT[]);
INSERT INTO temp_table VALUES (ARRAY[1,2]),(ARRAY[3,4]);
SELECT UNNEST(numbers) FROM temp_table;
unnest
--------
1
2
3
4

In the above example, a temporary table temp_table is created with one column numbers of type INT[]. The UNNEST function is then used on that column in a SELECT statement. The UNNEST function takes an array and returns a table with a single column containing all the elements of the array as separate rows. Thus, the output contains individual elements of the array in separate rows.