Sub topic 8
Converting between arrays and rows
This chapter assumes you can read basic SELECT, JOIN and GROUP BY queries, and that you have the posts table from earlier chapters. You should also know how array literals and subscripts work and how NULL behaves in SQL. Here you learn to move data in both directions: from one array value to many rows, and from many rows back to one array.
SQL operates on rows. Aggregates, joins, DISTINCT and ORDER BY all work on rows, not on elements inside a single value. When you need to count tags or deduplicate or reorder elements, you convert the array to rows, do the work, and convert it back.
Test data
The examples use the posts table from the first chapter. This script adds a third post with an empty array so you can see how empty arrays behave. If you already have a posts table, skip the CREATE TABLE and insert only the rows you are missing.
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
INSERT INTO posts (title, tags) VALUES
('Intro to arrays', ARRAY['sql', 'postgres']),
('Indexing', '{postgres,indexing,gin}'),
('Untagged draft', '{}');Arrays to rows with unnest
unnest is a set-returning function. It takes an array and returns one row per element. The simplest call needs no table.
SELECT * FROM unnest(ARRAY['a', 'b', 'c']);This returns three rows. To keep each element tied to the row it came from, use unnest in the FROM clause with LATERAL. LATERAL lets the function refer to columns of tables listed earlier in the same FROM. Adding WITH ORDINALITY produces a second column with the element's 1-based position.
SELECT p.id, t.tag, t.pos
FROM posts AS p
CROSS JOIN LATERAL unnest(p.tags) WITH ORDINALITY AS t(tag, pos);With the test data the result is:
| id | tag | pos |
|---|---|---|
| 1 | sql | 1 |
| 1 | postgres | 2 |
| 2 | postgres | 1 |
| 2 | indexing | 2 |
| 2 | gin | 3 |
The alias t(tag, pos) names the function's output columns. Without it, a single-column unnest produces a column named unnest, which is easy to misread in larger queries.
Posts with empty or NULL arrays disappear
Post 3 is missing from the table above. unnest of an empty array returns zero rows, and unnest of a NULL array also returns zero rows. A CROSS JOIN against zero rows removes the parent row. To keep every post, use a LEFT JOIN LATERAL with a condition that is always true.
SELECT p.id, t.tag, t.pos
FROM posts AS p
LEFT JOIN LATERAL unnest(p.tags) WITH ORDINALITY AS t(tag, pos) ON true
ORDER BY p.id, t.pos;Post 3 now appears once, with NULL for tag and pos. This matters whenever you count or report on all posts. A cross join silently drops the untagged ones.
NULL elements are preserved
If an array contains a NULL element, unnest returns it as a row with a NULL value. It does not skip it.
SELECT * FROM unnest(ARRAY['x', NULL, 'z']) WITH ORDINALITY AS t(val, pos);This returns three rows, and the second has val NULL at position 2. Filter with WHERE val IS NOT NULL if you do not want it. Do not write val <> NULL, which is never true.
Unnesting several arrays at once
You can pass more than one array to unnest in the FROM clause. The arrays are read in parallel, like a zip, and the shorter ones are padded with NULL.
SELECT *
FROM unnest(ARRAY[1, 2, 3], ARRAY['a', 'b']) AS t(n, letter);This returns (1, a), (2, b) and (3, NULL). It is useful when two columns hold parallel lists, but it is also a sign that those lists may belong in one related table.
Multidimensional arrays are flattened
unnest ignores dimensions. unnest(ARRAY[[1,2],[3,4]]) returns four rows: 1, 2, 3, 4, in row-major order. If you need one row per sub-array, subscript the array with generate_series instead.
Avoid unnest in the SELECT list
SELECT id, unnest(tags) FROM posts works, and it expands each post into several rows. Using it there has two problems. You cannot get the ordinality, and several set-returning functions in one SELECT list run in lockstep, which is easy to misread. Keep unnest in FROM.
Analysing elements with ordinary SQL
Once elements are rows, the usual tools apply. This query counts how often each tag is used across all posts.
SELECT tag, count(*) AS uses
FROM posts, unnest(tags) AS tag
GROUP BY tag
ORDER BY uses DESC, tag;The result is postgres with 2, then gin, indexing and sql with 1 each. This is a full table scan that expands every array. A GIN index (a later chapter) helps queries that look for specific values, but it does not make this kind of whole-table summary cheap.
Rows to arrays with array_agg
array_agg is an aggregate function that collects the values of a group into one array. By itself it makes no promise about the order of the elements. Put an ORDER BY inside the call to control it.
SELECT array_agg(DISTINCT tag ORDER BY tag) AS all_tags
FROM posts, unnest(tags) AS tag;This returns {gin,indexing,postgres,sql}. In an aggregate that uses DISTINCT, the ORDER BY expressions must appear in the argument list, which is why this call orders by tag itself.
You can also group by something else and collect a different column. This query lists the post ids for each tag, which is the reverse of how the data is stored.
SELECT tag, array_agg(p.id ORDER BY p.id) AS post_ids
FROM posts AS p, unnest(p.tags) AS tag
GROUP BY tag
ORDER BY tag;The result is gin {2}, indexing {2}, postgres {1,2} and sql {1}.
Filtering inside the aggregate
The FILTER clause limits which rows feed one aggregate. This is cleaner than a CASE expression inside the call.
SELECT p.id,
array_agg(t.tag ORDER BY t.pos) FILTER (WHERE t.tag <> 'sql') AS without_sql
FROM posts AS p
CROSS JOIN LATERAL unnest(p.tags) WITH ORDINALITY AS t(tag, pos)
GROUP BY p.id
ORDER BY p.id;Post 1 becomes {postgres} and post 2 stays {postgres,indexing,gin}. Ordering by t.pos keeps the original element order.
array_agg returns NULL for zero rows
If no rows reach array_agg, the result is NULL, not {}. If no rows reach it because of a FILTER, you also get NULL. If the column is NOT NULL, as tags is, writing that result back fails. Wrap the call in coalesce when you need an empty array.
SELECT coalesce(array_agg(tag), '{}') AS safe
FROM unnest('{}'::text[]) AS tag;Also, array_agg keeps NULL inputs as NULL elements. Remove them with FILTER (WHERE tag IS NOT NULL) if that is not what you want.
ARRAY(subquery)
When you only want to rebuild one array from one row's elements, a full GROUP BY is more than you need. The ARRAY(subquery) constructor takes a subquery that returns one column and turns its rows into an array.
SELECT id,
ARRAY(SELECT t FROM unnest(tags) AS t ORDER BY t) AS sorted_tags
FROM posts
ORDER BY id;This sorts the tags inside each post. The subquery is correlated to the outer row through tags, so there is no GROUP BY to write and no problem with rows that have no tags.
The two forms differ on empty input:
SELECT
ARRAY(SELECT tag FROM unnest('{}'::text[]) AS tag) AS from_constructor,
(SELECT array_agg(tag) FROM unnest('{}'::text[]) AS tag) AS from_aggregate;from_constructor is {} and from_aggregate is NULL. For per-row rewrites, the constructor gives an empty array without any coalesce.
Cleaning an array in place
Combining the two directions lets you normalise a column with a single statement. This one lowercases tags, trims whitespace, removes duplicates and sorts them.
UPDATE posts
SET tags = ARRAY(
SELECT DISTINCT lower(trim(t))
FROM unnest(tags) AS t
WHERE t IS NOT NULL
ORDER BY 1
);ORDER BY 1 refers to the first select-list expression, which is what SELECT DISTINCT requires. Rows that were empty stay {}. Run this inside a transaction and check the result with a SELECT first, because it rewrites every row.
Choosing between the two forms
| Situation | Use |
|---|---|
| Rebuild one array from the same row's elements | `ARRAY(subquery)` |
| Combine values from many rows into one array | `array_agg` with `GROUP BY` |
| Need to keep rows with empty or NULL arrays | `LEFT JOIN LATERAL ... ON true` |
| Need element positions | `WITH ORDINALITY` |
| Need an empty array instead of NULL from an aggregate | `coalesce(array_agg(...), '{}')` |
Common errors
- Missing rows after a join. A
CROSS JOINor comma join withunnestdrops rows whose array is empty or NULL. Switch toLEFT JOIN LATERAL ... ON true. - Unexpected order. Neither
unnestresults norarray_aggoutput has a guaranteed order unless you ask for one. UseWITH ORDINALITYgoing in andORDER BYinsidearray_aggcoming out. - NULL where
{}was expected.array_aggover no rows returns NULL. UseARRAY(subquery)orcoalesce. - Flattened dimensions.
unnestof a multidimensional array returns every element as a single list. - Slow summaries. Expanding every array in a large table reads and decompresses each value. If you run such counts often, that is a hint that the tags may belong in their own table.
Exercise
Write a query that returns every post id with its tags in alphabetical order as an array. Post 3, which has an empty array, must still appear with {} as its array, and the query must not use GROUP BY.
Show answer
SELECT id, ARRAY(SELECT t FROM unnest(tags) AS t ORDER BY t) AS sorted_tags FROM posts ORDER BY id; The ARRAY(subquery) constructor returns {} for zero rows and works per row, so no GROUP BY or coalesce is needed.
Exercise
This query is meant to list every post with the number of tags it has, but post 3 is missing from the result. Explain why and fix it. SELECT p.id, count(t.tag) AS n FROM posts AS p, unnest(p.tags) AS t(tag) GROUP BY p.id;
Show answer
The comma join is a cross join against unnest, and unnest of an empty array returns zero rows, so post 3 is dropped before grouping. Use a left join: SELECT p.id, count(t.tag) AS n FROM posts AS p LEFT JOIN LATERAL unnest(p.tags) AS t(tag) ON true GROUP BY p.id ORDER BY p.id; count(t.tag) ignores the NULL produced for post 3, so it reports 0. (cardinality(p.tags) would also give the count directly without any join.)
Exercise
What do these two expressions return, and why do they differ? (1) ARRAY(SELECT x FROM unnest('{}'::int[]) AS x) (2) (SELECT array_agg(x) FROM unnest('{}'::int[]) AS x)
Show answer
Expression 1 returns the empty array {}. Expression 2 returns NULL. The ARRAY constructor always builds an array, which is empty when the subquery has no rows. An aggregate over zero rows returns NULL, as array_agg does, so you would need coalesce to get {}.