Finding the previous row: non-equi self join (triangular join) → LATERAL, LAG

To get the time of the same customer's previous order for each order, a self join with "orders earlier than this one" followed by MAX produces rows proportional to the square of each customer's order count. The 5,428 orders of 10 high-volume customers blow up to 1.47 million rows. The fix is LATERAL, which finds only the one previous row, or LAG, which reads once and is done.

SQL

Situation

An analysis looks at order intervals of high-volume B2B customers. For each 2025 order of customers 1–10, the time of the same customer's immediately preceding order is attached to compute the order interval. SQL from the days before window functions was carried over as is: it joins "the orders earlier than this one" and takes the latest of them. The result is 5,428 rows, but adding more high-volume customers hits the time limit.

Tables

TableColumnsDescription
orderscust_id, ord_dt5,428 orders in 2025 for customers 1–10, about 540 per customer
IndexColumns
orders_x1cust_id, ord_dt

Query

BEFORE · Self join + MAX

SELECT o1.cust_id, o1.ord_id, o1.ord_dt, MAX(o2.ord_dt) AS prev_ord_dt
FROM orders o1
LEFT JOIN orders o2 ON o2.cust_id = o1.cust_id
                   AND o2.ord_dt >= TIMESTAMP '2025-01-01'
                   AND o2.ord_dt <  o1.ord_dt
WHERE o1.cust_id BETWEEN 1 AND 10
  AND o1.ord_dt >= TIMESTAMP '2025-01-01'
GROUP BY o1.cust_id, o1.ord_id, o1.ord_dt
ORDER BY o1.cust_id, o1.ord_dt

Compare the A-Rows of Nested Loop Left Join with the A-Rows of o1.

Approach

1. Compute the row count of the join result

Number a customer's orders 1, 2, …, n in time order; the k-th order joins with the k−1 earlier orders. One customer's join result is 0 + 1 + … + (n−1) ≈ n²/2 rows. Drawn as a table it is triangle-shaped, hence the name triangular join. With n = 540, one customer produces about 145,000 rows.

2. See how many rows are actually needed

MAX(o2.ord_dt) uses only the last one of the earlier orders. The other k−2 rows are built and then discarded by the aggregate. What is needed is "the last of the earlier orders", which is the single entry immediately before the position ord_dt < current order in the index (cust_id, ord_dt).

3. See whether it can be done without a join at all

Scanning once per customer in time order while remembering "the immediately preceding row" needs no join. The window function LAG does exactly that. Compare the cost of repeated probes (NL join) with a single scan (sort + window).

Explanation

1. LATERAL that finds only the one previous row

AFTER · One previous row (LATERAL + LIMIT 1)

SELECT o1.cust_id, o1.ord_id, o1.ord_dt, p.ord_dt AS prev_ord_dt
FROM orders o1
LEFT JOIN LATERAL (
  SELECT o2.ord_dt
  FROM orders o2
  WHERE o2.cust_id = o1.cust_id
    AND o2.ord_dt >= TIMESTAMP '2025-01-01'
    AND o2.ord_dt <  o1.ord_dt
  ORDER BY o2.ord_dt DESC
  LIMIT 1
) p ON true
WHERE o1.cust_id BETWEEN 1 AND 10
  AND o1.ord_dt >= TIMESTAMP '2025-01-01'
ORDER BY o1.cust_id, o1.ord_dt

Why it got faster

  • In Before, for each of the 5,428 o1 rows, Index Only Scan using orders_x1 reads all earlier orders (271 rows per iteration on average). The join result is 1,470,472 rows, and HashAggregate reduces it back to 5,428 rows. Buffers 23,231, execution time around 300ms. Only the index is read, so the block count is not large, but the row count is the problem. Adding customers grows the row count with the square of the order count.
  • After is the same NL join, but the inner side is Index Only Scan Backward + Limit of 1 row. Each iteration descends the index once and stops at one row. The join result is 5,428 rows. Buffers 17,411 (about 3 blocks per iteration), execution time around 50ms.
  • The row count dropped far more than Buffers did. In this scenario, also look at A-Rows and execution time.

2. LAG, which scans once and is done

AFTER · Window function LAG

SELECT cust_id, ord_id, ord_dt,
       LAG(ord_dt) OVER (PARTITION BY cust_id ORDER BY ord_dt) AS prev_ord_dt
FROM orders
WHERE cust_id BETWEEN 1 AND 10
  AND ord_dt >= TIMESTAMP '2025-01-01'
ORDER BY cust_id, ord_dt

Why it got faster

  • It reads the 5,428 orders once (Bitmap Heap Scan, 1,105 blocks), sorts them by (cust_id, ord_dt), and then WindowAgg attaches the value of the immediately preceding row. There are no repeated probes. Buffers 1,105, execution time around 10ms.
  • The outer ORDER BY matches the window's sort order, so there is only one sort.

Why this is optimal

  • With LAG, only the cost of reading the 5,428 result rows (1,030 table blocks + 75 index blocks) and their sort remain. Each row the result needs is read once, so there is nothing more to cut.
  • LATERAL adds one index probe per result row. Still, "the square of the largest group" is gone, so this shape is used where a window function is not an option (for example, when the previous row is found in a different table).

Variation: the problem is group size, not group count

TRY · Self join, customer 1 over all periods

SELECT o1.cust_id, o1.ord_id, o1.ord_dt, MAX(o2.ord_dt) AS prev_ord_dt
FROM orders o1
LEFT JOIN orders o2 ON o2.cust_id = o1.cust_id
                   AND o2.ord_dt < o1.ord_dt
WHERE o1.cust_id = 1
GROUP BY o1.cust_id, o1.ord_id, o1.ord_dt
ORDER BY o1.cust_id, o1.ord_dt
  • There is only one customer, but with no period condition there are 2,026 orders. The join result is 2,051,326 rows (≈ 2,026² / 2), more than for the 10 customers in Before.
  • Conversely, widening Before to customers 1–20 only doubles the join result to about 2.94 million rows. It grows linearly with the number of customers and quadratically with the number of orders per customer.

Key points

  • "Join with the earlier rows, then MAX/MIN/COUNT" is a triangular join. It builds n²/2 rows for group size n, so it is fast normally and suddenly slows down when one large group arrives.
  • Get previous/next values with LAG/LEAD and running values with SUM(…) OVER (ORDER BY …), computing them in one pass with window functions (SQL window functions).
  • If a join is truly needed, rewrite the inner side as ORDER BY … LIMIT 1 so that it stops at one row. An index (group key, sort key) is required.
  • If orders share the same timestamp, LAG and the < condition give different results (LAG picks the preceding row at the same timestamp; < picks an earlier timestamp). In this data order timestamps do not overlap. If they can, make the order unique, as in ORDER BY ord_dt, ord_id.