PostgreSQL – UNNEST Function
The unnest
function in PostgreSQL is used to transform an array or a set of values into a set of rows. This is particularly useful when you have a column that stores arrays or sets and you want to work with the individual elements within those arrays as separate rows.
Below is the basic syntax of using the unnest
function:
SELECT unnest(array_column) AS column_alias
FROM your_table;
Where:
array_column
is the name of the column that contains the arrays you want to unnest.
column_alias
is an alias that you can provide to the unnested elements. This will be the name of the resulting column in the output.
Here’s an example:
Let’s say you have a table named orders
with a column named product_ids
that stores an array of product IDs for each order:
CREATE TABLE orders
(order_id serial PRIMARY KEY,
product_ids integer[] );
INSERT INTO orders (product_ids)
VALUES
('{101, 102, 103}'),
('{104, 105}'),
('{106}');
You can use the unnest
function to retrieve each individual product ID as a separate row:
SELECT unnest(product_ids) AS product_id
FROM orders;
The output would be:
product_id
------------
101
102
103
104
105
106
(6 rows)