Sub topic 8
Converting Between PostgreSQL Arrays and Rows
This chapter assumes that you know SELECT, joins, grouping, and NULL behavior. It also assumes a table named posts with an integer id and a text[] column named tags.
An array stores several values in one column. A query often needs those values as separate rows so it can filter, count, sort, or join them. PostgreSQL provides unnest for expanding an array and array_agg or ARRAY(subquery) for collecting rows back into an array.
Expanding arrays with `unnest`
unnest is a set-returning function. It produces one result row for each array element.
SELECT p.id, u.tag
FROM posts AS p
CROSS JOIN LATERAL unnest(p.tags) AS u(tag);CROSS JOIN LATERAL allows the function to use p.tags from the current row. PostgreSQL permits a table function such as unnest to refer to earlier FROM items.
For example, if one post has tags = ARRAY['sql', 'postgres'], the query produces two rows:
| id | tag |
|---|---|
| 1 | sql |
| 1 | postgres |
A post with an empty array produces no rows. This is important when you count results or join the expanded values to another table.
Keeping the element position
Add WITH ORDINALITY when the original position matters. PostgreSQL numbers array positions starting at 1.
SELECT p.id, u.tag, u.position
FROM posts AS p
CROSS JOIN LATERAL unnest(p.tags)
WITH ORDINALITY AS u(tag, position)
ORDER BY p.id, u.position;The position lets you restore the original order after sorting or grouping.
Aggregating rows into arrays
array_agg collects values from several rows into one array. Use ORDER BY inside the aggregate when the order must be predictable.
SELECT p.id,
array_agg(u.tag ORDER BY u.position) AS tags_again
FROM posts AS p
CROSS JOIN LATERAL unnest(p.tags)
WITH ORDINALITY AS u(tag, position)
GROUP BY p.id;Without the inner ORDER BY, PostgreSQL does not promise the order of values in the resulting array.
You can also aggregate values from many posts:
SELECT array_agg(DISTINCT u.tag ORDER BY u.tag) AS all_tags
FROM posts AS p
CROSS JOIN LATERAL unnest(p.tags) AS u(tag);This returns one array containing each distinct tag found in the table.
Using `ARRAY(subquery)`
ARRAY(subquery) is useful when a query directly describes the values to collect. The subquery must return one column.
SELECT p.id,
ARRAY(
SELECT u.tag
FROM unnest(p.tags) AS u(tag)
ORDER BY u.tag
) AS sorted_tags
FROM posts AS p;This sorts each post's tags independently.
ARRAY(subquery) returns an empty array when the subquery returns no rows. By contrast, array_agg returns NULL when it has no input rows.
| Input rows | `array_agg(value)` | `ARRAY(SELECT value)` |
|---|---|---|
| No rows | `NULL` | Empty array `{}` |
Preserving posts with empty arrays
A CROSS JOIN LATERAL removes a post when unnest produces no rows. Use a left lateral join to keep that post:
SELECT p.id,
COALESCE(
array_agg(u.tag ORDER BY u.position)
FILTER (WHERE u.position IS NOT NULL),
'{}'::text[]
) AS rebuilt_tags
FROM posts AS p
LEFT JOIN LATERAL unnest(p.tags)
WITH ORDINALITY AS u(tag, position)
ON true
GROUP BY p.id;The FILTER condition distinguishes a real array element from the null-extended row created by the left join. It also preserves a genuine NULL element inside the original array.
A common transformation
A typical workflow is:
- Expand each array with
unnest. - Filter, join, or group the resulting rows.
- Aggregate the selected values with
array_agg. - Add
ORDER BYif the array order matters.
For example, this keeps only tags beginning with p and preserves their original order:
SELECT p.id,
COALESCE(
array_agg(u.tag ORDER BY u.position)
FILTER (WHERE u.tag LIKE 'p%'),
'{}'::text[]
) AS p_tags
FROM posts AS p
LEFT JOIN LATERAL unnest(p.tags)
WITH ORDINALITY AS u(tag, position)
ON true
GROUP BY p.id;Exercise
What is the difference between CROSS JOIN LATERAL unnest(tags) and LEFT JOIN LATERAL unnest(tags) ON true for a row whose array is empty?
Show answer
The cross join removes the row because unnest produces no matching rows. The left lateral join keeps the row with null-extended columns, which can then be converted to an empty array with COALESCE.