Sub topic 8
Computing a value once and reusing it
This chapter assumes you can write SELECT, WHERE, ORDER BY and LIMIT, and that you know subqueries in FROM and table aliases. It also assumes you have seen CROSS JOIN LATERAL from the earlier chapters. Here you will use a lateral subquery for a different purpose. It doesn't fetch rows from another table. It gives a name to an expression so that the rest of the query can reuse it.
The problem: select-list aliases are not visible
Suppose each order stores a gross amount that includes 20% tax. You want the net amount and the tax. The natural attempt reuses the alias net in the same select list:
SELECT id, gross / 1.2 AS net, gross - net AS tax
FROM orders;
-- ERROR: column "net" does not existSQL evaluates the select list after FROM, WHERE and GROUP BY. Aliases defined in the select list do not exist yet when those clauses run. Even inside the select list, one expression cannot see the alias of its sibling. ORDER BY is the only clause that may use output aliases, and only as a bare name, not inside an expression.
The usual workarounds are repeating the expression, wrapping the query in an outer SELECT, or using a CTE. All of them add noise. A lateral subquery is a shorter alternative.
A subquery with no FROM clause
A SELECT does not need a FROM clause. SELECT 1 + 1 AS two returns exactly one row. When such a subquery sits in the FROM clause of another query with LATERAL, it can refer to columns of the tables to its left. It returns one row for each outer row, and its output columns become ordinary columns of the join.
Here is a small data set you can run as shown:
CREATE TEMP TABLE orders (
id int PRIMARY KEY,
gross numeric(12,2) NOT NULL,
discount_pct numeric(5,2) NOT NULL DEFAULT 0
);
INSERT INTO orders (id, gross, discount_pct) VALUES
(1, 120.00, 0),
(2, 59.90, 10),
(3, 240.00, 25);Now compute net once and use it twice:
SELECT o.id, n.net, o.gross - n.net AS tax
FROM orders o
CROSS JOIN LATERAL (SELECT round(o.gross / 1.2, 2) AS net) AS n
ORDER BY o.id;| id | net | tax |
|---|---|---|
| 1 | 100.00 | 20.00 |
| 2 | 49.92 | 9.98 |
| 3 | 200.00 | 40.00 |
The subquery n is evaluated for each row of o. It reads o.gross, which is legal because of LATERAL. The name n.net is now a normal column, so the select list, WHERE, GROUP BY and ORDER BY can all use it.
Because the subquery has no FROM and no WHERE, it always returns exactly one row. That makes CROSS JOIN safe. The outer row count does not change, and no outer row is dropped.
Chaining several steps
A later lateral item can refer to an earlier one. This lets you write a calculation as a sequence of named steps, where each step builds on the previous one:
SELECT o.id, d.price, n.net, t.tax
FROM orders o
CROSS JOIN LATERAL (
SELECT round(o.gross * (1 - o.discount_pct / 100), 2) AS price
) AS d
CROSS JOIN LATERAL (
SELECT round(d.price / 1.2, 2) AS net
) AS n
CROSS JOIN LATERAL (
SELECT d.price - n.net AS tax
) AS t
WHERE t.tax >= 10
ORDER BY t.tax DESC;| id | price | net | tax |
|---|---|---|---|
| 3 | 180.00 | 150.00 | 30.00 |
| 1 | 120.00 | 100.00 | 20.00 |
Order 2 has a tax of 8.98, so the WHERE clause removes it. Three things are worth noticing:
- Each step has a name (
price,net,tax) that says what it means. The finalWHEREandORDER BYread like the business rule. - The steps run in the order written.
ncan usedbecausedappears before it inFROM. Reversing the order gives an error, as the join-type chapter explains. - Changing the tax rate means editing one number in one place.
Returning more than one column
A lateral subquery can return several columns at once. This is useful when one calculation produces related values, such as a quotient and a remainder, or a parsed date and a flag:
SELECT o.id, p.whole, p.cents
FROM orders o
CROSS JOIN LATERAL (
SELECT trunc(o.gross)::int AS whole,
(round(o.gross * 100)::int) % 100 AS cents
) AS p
ORDER BY o.id;For order 2 (59.90) this returns whole = 59 and cents = 90.
A VALUES list works the same way and can produce several rows per outer row. This turns columns into rows, sometimes called unpivoting:
SELECT o.id, m.label, m.amount
FROM orders o
CROSS JOIN LATERAL (
VALUES
('gross', o.gross),
('discount', round(o.gross * o.discount_pct / 100, 2))
) AS m(label, amount)
ORDER BY o.id, m.label;Each order now produces two rows, one labeled discount and one labeled gross. Here the row count does change, so the one-row guarantee from the previous section no longer applies.
Does it really compute once?
The phrase "compute once" describes what you write. It does not always describe what PostgreSQL executes.
For a simple subquery such as SELECT o.gross / 1.2 AS net, the planner usually flattens it into the outer query. This is called subquery pull-up. After flattening, the expression o.gross / 1.2 may appear in several places in the plan. That is harmless for a cheap, deterministic expression, because the result is identical either way.
The difference shows up with volatile functions, which can return a different value on every call. random() and clock_timestamp() are examples. PostgreSQL does not flatten a subquery that has a volatile function in its select list. The subquery stays a separate step and is evaluated once for each outer row:
SELECT o.id, r.roll, round(r.roll * 100) AS pct
FROM orders o
CROSS JOIN LATERAL (SELECT random() AS roll) AS r;In every output row, roll and the value used for pct come from the same call. Compare this with writing random() and random() * 100 in the select list. Those are two separate calls, so the two columns would be unrelated.
Compared with other approaches
| Approach | Name usable in WHERE and ORDER BY | Can read outer columns | Notes |
|---|---|---|---|
| Repeat the expression | Yes, by retyping it | Yes | Easy to let copies drift apart |
| Outer `SELECT` over an inner query | Yes | Yes | Adds nesting and an extra alias |
| CTE (`WITH`) | Yes | Only its own tables | Good when the value is needed by many queries |
| `CROSS JOIN LATERAL (SELECT ...)` | Yes | Yes | Steps can chain; stays inside one `FROM` |
| Generated column | Yes | Same row only | Stored on disk; only for fixed, deterministic formulas |
Use a generated column when the formula is part of the data model and every query needs it. Use a lateral subquery when the calculation belongs to one query.
Pitfalls
Name clashes
If a lateral column has the same name as a column in another FROM item, an unqualified reference becomes ambiguous:
-- If orders also had a column named net, this would fail:
-- ERROR: column reference "net" is ambiguous
SELECT net FROM orders o CROSS JOIN LATERAL (SELECT o.gross / 1.2 AS net) AS n;Qualify the reference as n.net, or pick distinct names.
A WHERE clause can remove the row
The one-row guarantee holds only when the subquery has no FROM clause and no WHERE, or when its WHERE is always true. Add WHERE o.gross > 100 inside the lateral subquery and it returns zero rows for small orders. With CROSS JOIN, those orders vanish from the result. If you want to keep the outer row, use LEFT JOIN LATERAL (...) AS n ON true, and the lateral columns become NULL. Usually the better fix is to put the filter in the outer WHERE.
NULL propagates
If o.gross is NULL, then n.net is NULL. The row still exists, because a lateral subquery with no FROM clause returns one row containing a null. Nothing is skipped silently, but later arithmetic on n.net also yields NULL.
Use it for clarity, not for every expression
A lateral subquery for o.a + 1 that you use once is not worth it. The pattern pays off when the expression is long, used in several places, or part of a chain of steps.
Exercise
A table trips(id, distance_km numeric, minutes numeric) is given. Write a query that returns id, speed (distance_km divided by minutes, times 60, rounded to 1 decimal) and slow (true when speed is below 30). Compute the speed only once in the text of the query, and return only the trips with minutes > 0.
Show answer
SELECT t.id, s.speed, s.speed < 30 AS slow FROM trips t CROSS JOIN LATERAL ( SELECT round(t.distance_km / t.minutes * 60, 1) AS speed ) AS s WHERE t.minutes > 0; The filter in the outer WHERE prevents a division by zero. Because the subquery has no FROM clause it returns one row per trip, so no trips are lost to the join.
Exercise
Why does SELECT gross / 1.2 AS net, gross - net AS tax FROM orders fail, and why does the LATERAL version fix it? What would change if the lateral subquery contained WHERE gross > 100 and you kept CROSS JOIN?
Show answer
Output aliases from the select list are not visible to other expressions in the same list, because aliases are only assigned after the expressions are evaluated. In the lateral version, net is a column of a FROM item, and FROM items are visible to the select list. If the subquery had WHERE gross > 100, it would return no row for orders with a gross of 100 or less, and CROSS JOIN would drop those orders from the result. Use LEFT JOIN LATERAL ... ON true to keep them (with NULL net), or move the condition to the outer WHERE.