Sub topic 6
Set-returning functions in FROM
This chapter assumes you can write SELECT, JOIN and LEFT JOIN, and that you have seen CROSS JOIN LATERAL and LEFT JOIN LATERAL ... ON true in the earlier chapters. It uses PostgreSQL 12 or later.
What a set-returning function is
A set-returning function (SRF) is a function that returns zero or more rows instead of a single value. You have probably used one already:
SELECT * FROM generate_series(1, 3) AS g(n);This returns three rows, with values 1, 2 and 3. The function sits in the FROM clause and acts like a table.
The functions you will use most often are:
| Function | What it returns |
|---|---|
| `generate_series(start, stop[, step])` | One row per value in the range |
| `unnest(array)` | One row per array element |
| `jsonb_array_elements(jsonb)` | One row per element of a JSON array |
| `regexp_matches(text, pattern, 'g')` | One row per regular expression match |
| `string_to_table(text, delimiter)` | One row per delimited piece of a string (PostgreSQL 14+) |
Constant arguments are not very interesting. The useful case is an SRF whose arguments come from another table, so that every row of that table is expanded into several rows. That is what LATERAL gives you.
Functions in FROM are implicitly lateral
For a subquery you must write the LATERAL keyword, or PostgreSQL rejects any reference to an earlier FROM item. For a function call in FROM, the keyword is optional. PostgreSQL lets a function's arguments refer to earlier FROM items either way. These two queries are the same:
SELECT p.id, u.tag
FROM posts p
CROSS JOIN LATERAL unnest(p.tags) AS u(tag);
SELECT p.id, u.tag
FROM posts p, unnest(p.tags) AS u(tag);The second form uses a comma join, which is a cross join. It works because function calls are implicitly lateral. Many people write the explicit CROSS JOIN LATERAL anyway, because it shows the per-row dependency to the next reader.
The semantics are the ones you already know. For each row of posts, PostgreSQL calls unnest with that row's tags, and the join pairs the post row with every row the function returns.
Example: one row per array element
The examples in this chapter use this setup. You can run it in any scratch database.
CREATE TABLE posts (
id int PRIMARY KEY,
tags text[]
);
INSERT INTO posts (id, tags) VALUES
(1, ARRAY['sql', 'postgres', 'lateral']),
(2, ARRAY[]::text[]),
(3, NULL),
(4, ARRAY['indexes']);Now expand each post's tags into rows, and add the position of each tag in its array:
SELECT p.id, u.tag, u.pos
FROM posts p
CROSS JOIN LATERAL unnest(p.tags) WITH ORDINALITY AS u(tag, pos);The result is:
| id | tag | pos |
|---|---|---|
| 1 | sql | 1 |
| 1 | postgres | 2 |
| 1 | lateral | 3 |
| 4 | indexes | 1 |
WITH ORDINALITY adds a bigint column that numbers the rows each function call returns, starting at 1. The numbering restarts for every call, so here it restarts for every post. It always becomes the last column, which is why the alias list is u(tag, pos): the first name is for the function's own column, the second for the ordinality column.
Posts 2 and 3 are missing from the result. An empty array and a NULL array both make unnest return zero rows, and a cross join of one row with zero rows is zero rows. This is the same behavior as CROSS JOIN LATERAL with a subquery that returns nothing.
Keeping rows whose function returns nothing
To keep those posts, use LEFT JOIN LATERAL ... ON true, as you did with subqueries:
SELECT p.id, u.tag, u.pos
FROM posts p
LEFT JOIN LATERAL unnest(p.tags) WITH ORDINALITY AS u(tag, pos) ON true
ORDER BY p.id, u.pos;Posts 2 and 3 now appear once each, with NULL in tag and pos. You cannot tell from the output alone whether a post had an empty array or a NULL array. If that distinction matters, select p.tags as well.
ON true is needed because the join syntax requires an ON or USING clause for LEFT JOIN. The lateral reference already ties each function call to its row, so there is nothing left to match on.
Naming the output columns
A function's output columns get names from the alias list, and the rules differ by function type.
- With no alias,
unnestreturns a column namedunnest. This is easy to forget and produces confusing queries. - A function that returns a single base-type column, such as
unnest(text[]), gets that column renamed when you give a table alias without a column list.FROM unnest(p.tags) AS tagnames both the table alias and the columntag. - If you add a column list, it must match the number of columns, including the ordinality column. A shorter list renames only the first columns and leaves the rest with their default names. A longer list is an error.
I recommend always writing the full list, as in AS u(tag, pos). The query then says what each column is, and it does not depend on the function's default names.
-- Table alias and column both called tag
SELECT p.id, tag
FROM posts p, unnest(p.tags) AS tag;generate_series with per-row bounds
generate_series becomes a different tool when its bounds come from a table. Suppose each hotel booking has a check-in and a check-out date and you want one row per night:
CREATE TABLE bookings (
id int PRIMARY KEY,
check_in date NOT NULL,
check_out date NOT NULL
);
INSERT INTO bookings VALUES
(1, DATE '2026-12-24', DATE '2026-12-27'),
(2, DATE '2026-12-31', DATE '2026-12-31');
SELECT b.id, d.night::date AS night
FROM bookings b
CROSS JOIN LATERAL generate_series(
b.check_in,
b.check_out - 1,
interval '1 day'
) AS d(night);Booking 1 gives three nights: 24, 25 and 26 December. Booking 2 gives none, because check_out - 1 is earlier than check_in, and generate_series returns no rows when the start is already past the stop.
The dates are cast to date at the end because generate_series with date arguments and an interval step returns timestamp with time zone. Without the cast you would see midnight timestamps in your session's time zone.
The same pattern works with integer bounds. generate_series(1, o.qty) repeats an order line once per unit ordered, which is useful for creating label-printing rows or test data.
Several arrays in step: multi-argument unnest and ROWS FROM
unnest accepts several arrays in FROM and returns them side by side:
SELECT *
FROM unnest(ARRAY[1, 2, 3], ARRAY['a', 'b']) AS t(n, letter);| n | letter |
|---|---|
| 1 | a |
| 2 | b |
| 3 | NULL |
The shorter array is padded with NULLs. This is useful when a table keeps parallel arrays, such as skus text[] and qtys int[], and you want to pair the nth element of each. Do not use two separate unnest calls as separate FROM items for this: that is a cross join, and it gives 3 × 2 = 6 rows.
ROWS FROM generalizes this to any mix of set-returning functions, and each function can have its own column definitions:
SELECT *
FROM ROWS FROM (
generate_series(10, 30, 10),
unnest(ARRAY['x', 'y'])
) AS t(num, label);This gives rows (10, x), (20, y) and (30, NULL). As with multi-argument unnest, the function that runs out first is padded with NULL. ROWS FROM can also be combined with WITH ORDINALITY, in which case the ordinality column numbers the combined rows.
Why not put the function in the select list?
PostgreSQL also accepts SRFs in the select list:
SELECT id, unnest(tags) AS tag FROM posts;This looks shorter, but I advise against it for new code, for these reasons:
- Rows with an empty or NULL array disappear, and you cannot change that without rewriting the query. In FROM you can switch to
LEFT JOIN LATERAL. - You cannot filter on the function's output in the same query level's
WHERE, becauseWHEREis evaluated before the select list. In FROM, the function's columns are ordinary columns and you can filter withWHERE u.tag = 'sql'. - With two SRFs in the select list, PostgreSQL 10 and later run them in step and pad the shorter one with NULLs. Older versions produced a least-common-multiple number of rows. Nobody should have to remember which behavior applies.
- You cannot use
WITH ORDINALITYthere.
A clean FROM-clause SRF reads the same on every supported version and plays well with the other join types.
Filtering and aggregating the expanded rows
Once the function is in FROM, the expanded rows are ordinary rows. You can filter them, group them and join them to other tables.
-- How often does each tag appear?
SELECT u.tag, count(*) AS uses
FROM posts p
CROSS JOIN LATERAL unnest(p.tags) AS u(tag)
GROUP BY u.tag
ORDER BY uses DESC, u.tag;
-- Which posts have the tag 'sql', and at which position?
SELECT p.id, u.pos
FROM posts p
CROSS JOIN LATERAL unnest(p.tags) WITH ORDINALITY AS u(tag, pos)
WHERE u.tag = 'sql';The second query still expands every array before filtering. For a pure membership test, WHERE 'sql' = ANY (p.tags) or p.tags @> ARRAY['sql'] avoids the expansion and can use a GIN index. Use unnest when you need the individual elements as rows, and use array operators when you only need to ask a question about the array.
Common errors
ERROR: invalid reference to FROM-clause entry for table "p"with the hint that the combining JOIN type must be INNER or LEFT. A function in FROM refers to a table that sits on the preserved side of aRIGHTorFULLjoin. Reorder the tables or change the join type.- Function arguments referring to a table listed later. FROM items can only see items before them, so move the function after the table it uses.
function unnest(text) does not exist. The column holds text, not an array. Check the column type, or cast it with something likestring_to_array(col, ',').- Missing rows. A cross join dropped rows whose function returned nothing. Switch to
LEFT JOIN LATERAL ... ON trueif you want them kept. - Unexpected row multiplication. Two SRFs in separate FROM items multiply. Use multi-argument
unnestorROWS FROMwhen you want them in step.
Performance notes
A function in FROM is evaluated once per row of the left side. Whether that is cheap depends on what the function does.
unneston an array already in memory is very cheap. The cost is proportional to the number of elements produced.- Planner row estimates for SRFs are a known weak spot. A function declared without a
ROWSvalue is assumed to return 1000 rows, and recent versions give built-ins such asgenerate_seriesandunnestbetter estimates in simple cases. A bad estimate can lead the planner to choose a poor join strategy for the rows that follow, so checkEXPLAINwhen a query with an SRF is slow. - The plan node is
Function Scan. In a lateral query it appears on the inner side of aNested Loop, andloopsinEXPLAIN ANALYZEshows how many times it ran.
EXPLAIN (ANALYZE)
SELECT p.id, u.tag
FROM posts p
CROSS JOIN LATERAL unnest(p.tags) AS u(tag);On a large posts table you will see a Function Scan on unnest with loops equal to the number of posts. That is expected. If the loop count is far higher than you thought, check whether an earlier join multiplied the left side before the function ran.
The next chapter applies the same pattern to JSON: jsonb_array_elements is just another set-returning function in FROM.
Summary of the pattern
- Put the SRF after the table whose columns it needs.
- Use
CROSS JOIN LATERAL(or a comma) to drop rows with no output, andLEFT JOIN LATERAL ... ON trueto keep them. - Name every output column with an alias list, and remember that the ordinality column comes last.
- Use multi-argument
unnestorROWS FROMto combine functions in step, and separate FROM items only when you want a Cartesian product.
Exercise
Using the posts table from this chapter, write a query that returns every post id together with each of its tags and the tag's position, but keeps posts whose tags array is empty or NULL (showing NULL for tag and position). Then say what happens to those posts if you change LEFT JOIN LATERAL ... ON true to CROSS JOIN LATERAL.
Show answer
SELECT p.id, u.tag, u.pos FROM posts p LEFT JOIN LATERAL unnest(p.tags) WITH ORDINALITY AS u(tag, pos) ON true ORDER BY p.id, u.pos; With CROSS JOIN LATERAL, unnest returns zero rows for an empty or NULL array, so posts 2 and 3 disappear from the result.
Exercise
A table orders(id int, skus text[], qtys int[]) stores two parallel arrays of equal length. Write a query that returns one row per order line with id, sku and qty. Why is calling unnest(o.skus) and unnest(o.qtys) as two separate FROM items the wrong approach?
Show answer
SELECT o.id, l.sku, l.qty FROM orders o CROSS JOIN LATERAL unnest(o.skus, o.qtys) AS l(sku, qty); Two separate FROM items are joined as a Cartesian product, so an order with 3 SKUs and 3 quantities would give 9 rows, pairing every SKU with every quantity. Multi-argument unnest in a single FROM item returns the arrays side by side.