Sub topic 11
When to Use Something Other Than LATERAL
Assume you know basic SELECT, joins, subqueries, ORDER BY, and LIMIT. This chapter compares LATERAL with two common alternatives: window functions and correlated scalar subqueries.
LATERAL is useful when the right side of a FROM clause needs values from the current left-side row. However, it is not automatically the best choice. The amount of data, the result shape, and the number of values you need should guide your choice.
Use a window function for ranking many rows
A window function calculates a value across related rows without collapsing them into one row. For example, row_number() can number orders separately for each customer.
WITH ranked_orders AS (
SELECT
o.id,
o.customer_id,
o.total,
o.created_at,
row_number() OVER (
PARTITION BY o.customer_id
ORDER BY o.created_at DESC, o.id DESC
) AS order_number
FROM orders AS o
)
SELECT id, customer_id, total, created_at
FROM ranked_orders
WHERE order_number <= 3
ORDER BY customer_id, order_number;PARTITION BY defines each group. Here, each customer gets a separate numbering sequence. The outer query keeps the first three rows in each sequence.
This approach is often clearer when you need to rank, filter, or return several categories from the same set of rows. You can also return the fourth or fifth row, calculate running totals, or compare each row with the previous row.
A lateral query can stop reading after three matching rows when an appropriate index exists. A window query usually reads and ranks all rows that reach the window operation. That can make LATERAL faster for a small top-N result from many large groups. On the other hand, a window function may be better when most rows are needed anyway.
Use a scalar subquery for one value
A scalar subquery is a subquery that returns one value. It can be correlated with the current row, so it often solves a simpler problem than a lateral join.
SELECT
c.id,
c.name,
(
SELECT o.total
FROM orders AS o
WHERE o.customer_id = c.id
ORDER BY o.created_at DESC, o.id DESC
LIMIT 1
) AS latest_order_total
FROM customers AS c
ORDER BY c.id;The inner query runs in the context of one customer and returns that customer's latest order total. If no order exists, the scalar subquery returns NULL.
Use this form when you need one value in the SELECT list. It avoids creating a joined row source and is often easy to read.
A scalar subquery must return at most one row. If you remove LIMIT 1 and a customer has two matching orders, PostgreSQL raises an error:
ERROR: more than one row returned by a subquery used as an expressionUse an aggregate when the value can be summarized safely:
SELECT
c.id,
c.name,
(
SELECT max(o.created_at)
FROM orders AS o
WHERE o.customer_id = c.id
) AS latest_order_at
FROM customers AS c;The aggregate always returns one value for each customer, including NULL when no order matches.
Compare the result shapes
The main difference is what each technique returns.
| Technique | Best result shape | Typical use |
|---|---|---|
| `LATERAL` | Zero, one, or many right-side rows per left row | Top three orders with order columns |
| Window function | Many ranked or annotated rows | Top-N filtering, running totals, comparisons |
| Scalar subquery | One value per outer row | Latest timestamp or one calculated amount |
Choose LATERAL when the right side naturally behaves like a small, parameterized table. Choose a scalar subquery when it is really just one value. Choose a window function when the query needs to inspect and rank a broader result set.
Check the plan before deciding
Do not choose only from query appearance. Use EXPLAIN (ANALYZE, BUFFERS) to measure the actual plan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT
c.id,
(
SELECT o.total
FROM orders AS o
WHERE o.customer_id = c.id
ORDER BY o.created_at DESC, o.id DESC
LIMIT 1
) AS latest_total
FROM customers AS c;For a correlated lookup, an index beginning with the correlation column and continuing with the ordering columns can help:
CREATE INDEX orders_customer_created_id_idx
ON orders (customer_id, created_at DESC, id DESC);Compare the alternatives on realistic data. Look at execution time, rows examined, buffer reads, and whether the index is used. A query that is faster for ten customers may behave differently for a million customers.
Exercise
Exercise
You need each customer's latest order timestamp, but no other order columns. Should you start with LATERAL, a window function, or a scalar subquery?
Show answer
Start with a correlated scalar subquery using MAX(created_at), because the required result is one value per customer. Compare its measured plan with alternatives if performance matters.