Sub topic 8
Computing a Value Once and Reusing It
Assume you know basic SELECT statements, table aliases, and joins. This chapter focuses on a small but useful pattern: use LATERAL to calculate a value for each row, give that value a name, and reuse the name in the rest of the query.
Why a lateral subquery helps
A select-list alias usually cannot be reused by another expression in the same SELECT list:
-- This does not work
SELECT
id,
gross / 1.2 AS net,
net * 0.2 AS tax
FROM orders;PostgreSQL reports that the column net does not exist. Select-list aliases are assigned after the expressions in that list are evaluated. The alias is available to an outer query, but not to a sibling expression in the same list.
You can repeat the expression instead:
SELECT
id,
gross / 1.2 AS net,
(gross / 1.2) * 0.2 AS tax
FROM orders;That works, but the formula is duplicated. A lateral subquery gives the formula a reusable column name.
Reusing a value with `CROSS JOIN LATERAL`
A LATERAL subquery can read columns from tables that appear before it in the FROM clause. PostgreSQL evaluates the subquery in the context of each current row from the earlier table.
SELECT
o.id,
n.net,
n.net * 0.2 AS tax,
n.net * 1.2 AS total
FROM orders AS o
CROSS JOIN LATERAL (
SELECT o.gross / 1.2 AS net
) AS n;For every order, the subquery calculates o.gross / 1.2. The result has a column named net. The outer query can refer to n.net several times.
The CROSS JOIN produces one output row when the lateral subquery produces one row. This subquery has no FROM clause and always returns one row, even when o.gross is NULL. In that case, net, tax, and total are also NULL.
The same idea can make a longer expression easier to read:
SELECT
o.id,
p.net,
p.tax,
p.net + p.tax AS amount_due
FROM orders AS o
CROSS JOIN LATERAL (
SELECT
round(o.gross / 1.2, 2) AS net,
round((o.gross / 1.2) * 0.2, 2) AS tax
) AS p;Here, the lateral subquery creates two named values. The outer query combines them without repeating the original expressions.
The logical evaluation model
Think of the query as following this process:
- PostgreSQL takes one row from
orders. - The lateral subquery evaluates expressions using that order's columns.
- The subquery produces the derived columns.
- The outer
SELECTuses those columns. - PostgreSQL repeats the process for the next order.
This is a logical model. It explains the result and the scope of each reference. It does not promise that PostgreSQL will always perform a separate physical calculation for every reference. The query planner may simplify or inline simple expressions. Use LATERAL primarily to express dependencies and improve clarity, not as a guaranteed materialization boundary.
If you need to force an intermediate result to be stored for a query, consider a materialized common table expression or a temporary table. Those choices have different performance and maintenance costs.
> callout note > A lateral subquery gives an expression a reusable column name. It does not automatically guarantee that PostgreSQL computes the expression only once in the physical execution plan.
Filtering by the derived value
The derived column is also available to clauses in the outer query:
SELECT
o.id,
n.net,
n.net * 0.2 AS tax
FROM orders AS o
CROSS JOIN LATERAL (
SELECT round(o.gross / 1.2, 2) AS net
) AS n
WHERE n.net > 100
ORDER BY n.net DESC;This avoids repeating the calculation in WHERE and ORDER BY. It also gives the calculation one place to change if the business rule changes.
A lateral subquery can return more than one column or more than one row. When it returns multiple rows, the outer row appears once for each returned row. For simple expression reuse, keep the subquery to one row per outer row so that it does not unexpectedly multiply results.
Choosing this pattern
Use a lateral calculation when:
- An expression is long or difficult to read.
- Several output expressions use the same derived value.
- A filter or sort should use the derived value by name.
- The calculation depends on the current row from an earlier
FROMitem.
A regular subquery may be enough when the calculation does not depend on an outer table. A select-list expression is often simpler when the value is used only once.
Exercise
Why does CROSS JOIN LATERAL (SELECT o.gross / 1.2 AS net) AS n allow the outer query to use n.net, while a select-list alias cannot be reused by a sibling expression?
Show answer
The lateral subquery produces net as a column of a row source before the outer SELECT list is evaluated. A select-list alias is assigned during output-column evaluation and is not visible to sibling expressions in that same list.