Sub topic 6
Set-Returning Functions in `FROM`
This chapter assumes you know basic SELECT, joins, table aliases, arrays, JSONB, and subqueries in FROM. It also assumes you understand that LATERAL lets a FROM item refer to columns from items listed before it.
A set-returning function is a function that produces zero or more rows. PostgreSQL can call such a function in the FROM clause. When the function uses a column from an earlier table, LATERAL makes the relationship explicit and easy to reason about.
Expanding an array with `unnest`
unnest converts an array into one row per element. For example, suppose posts.tags is a text[] column:
CREATE TABLE posts (
id bigint,
title text,
tags text[]
);
INSERT INTO posts (id, title, tags)
VALUES
(1, 'PostgreSQL tips', ARRAY['sql', 'postgresql']),
(2, 'Database indexes', ARRAY['performance']),
(3, 'Empty tags', ARRAY[]::text[]);You can expand each post's tags like this:
SELECT p.id, p.title, u.tag
FROM posts AS p
CROSS JOIN LATERAL unnest(p.tags) AS u(tag);The function receives the tags value from the current post. PostgreSQL produces one result row for each tag.
| id | title | tag |
|---|---|---|
| 1 | PostgreSQL tips | sql |
| 1 | PostgreSQL tips | postgresql |
| 2 | Database indexes | performance |
The third post produces no row because its array is empty. CROSS JOIN LATERAL keeps only rows for which the lateral item returns at least one row.
LATERAL is optional for some functions in FROM, but writing it makes the per-row dependency clear. It also keeps the query consistent when you later replace the function with a subquery.
Keeping array positions with `WITH ORDINALITY`
Sometimes the position of an array element matters. Add WITH ORDINALITY to receive a one-based position:
SELECT p.id, u.tag, u.pos
FROM posts AS p
CROSS JOIN LATERAL unnest(p.tags)
WITH ORDINALITY AS u(tag, pos)
ORDER BY p.id, u.pos;The alias list names the output columns. Here, tag is the array value and pos is its position.
Generating rows with `generate_series`
generate_series returns a sequence of numbers, dates, or timestamps. With LATERAL, each source row can define its own sequence.
CREATE TABLE subscriptions (
id bigint,
starts_on date,
ends_on date
);
SELECT s.id, d.day
FROM subscriptions AS s
CROSS JOIN LATERAL generate_series(
s.starts_on,
s.ends_on,
interval '1 day'
) AS d(day)
ORDER BY s.id, d.day;For each subscription, PostgreSQL generates one row per day from starts_on through ends_on. This is useful for calendars, reporting periods, and filling time ranges.
A function can return no rows. For example, if the start date is after the end date, the CROSS JOIN LATERAL removes that subscription from the result.
Use LEFT JOIN LATERAL when you need to keep the source row:
SELECT s.id, d.day
FROM subscriptions AS s
LEFT JOIN LATERAL generate_series(
s.starts_on,
s.ends_on,
interval '1 day'
) AS d(day) ON true;For a subscription with no generated dates, d.day is NULL.
Expanding JSON arrays
PostgreSQL's jsonb_array_elements turns each element of a JSONB array into a row:
SELECT o.id,
i.item ->> 'sku' AS sku,
(i.item ->> 'qty')::integer AS qty
FROM orders AS o
CROSS JOIN LATERAL jsonb_array_elements(o.items) AS i(item);If o.items contains:
[
{"sku": "A-10", "qty": 2},
{"sku": "B-20", "qty": 1}
]the query returns two rows. The ->> operator extracts a JSON value as text. The cast to integer converts the quantity into a numeric SQL value.
For a JSON array of scalar strings, use the text-returning function:
SELECT o.id, item.value
FROM orders AS o
CROSS JOIN LATERAL jsonb_array_elements_text(o.items) AS item(value);Choose the function based on the JSON shape. Use jsonb_array_elements when each element is an object that you will inspect with JSON operators. Use jsonb_array_elements_text when each element is already a scalar value.
Common errors
A function in FROM must have an alias when you want to reference its output columns. Also, remember that CROSS JOIN LATERAL discards source rows whose function returns no rows. If that is not the desired behavior, use LEFT JOIN LATERAL ... ON true.
Exercise
Which join should you use to expand an array while retaining a parent row whose array is empty?
Show answer
Use LEFT JOIN LATERAL with ON true. The expanded columns become NULL when the function returns no rows.