First and last value in a partition
Two window functions, one frame each. LAST_VALUE needs the full frame or it lies.
The task
You want every order row to show the customer's first and most recent order amount, so you can compute change since the first order inline.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT customer_id, order_date, amount,
FIRST_VALUE(amount) OVER (PARTITION BY customer_id
ORDER BY order_date, id
ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING) AS first_order_amount,
LAST_VALUE(amount) OVER (PARTITION BY customer_id
ORDER BY order_date, id
ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING) AS last_order_amount
FROM orders;
Fonctionnement
FIRST_VALUE with an ordered window is straightforward: the first row of the partition. LAST_VALUE is the famous trap, because the default frame stops at the current row, which makes it return the current row's own value; extending the frame to UNBOUNDED FOLLOWING makes it see the whole partition. Both calls repeat the same OVER clause; the variant names it once with a WINDOW clause, which SQL Server accepts from 2022 (compatibility level 160) and Oracle from 21c.
Variations
Named WINDOW clause (PostgreSQL, MySQL, SQLite, Oracle 21c+, SQL Server 2022+)
SQL Server PostgreSQL MySQL SQLite OracleSELECT customer_id, order_date, amount,
FIRST_VALUE(amount) OVER w AS first_order_amount,
LAST_VALUE(amount) OVER w AS last_order_amount
FROM orders
WINDOW w AS (PARTITION BY customer_id
ORDER BY order_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING);
Questions that come up
Why does LAST_VALUE return the current row by default?
Because the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and 'current row' includes its peers. The function is doing what the frame says; extend the frame to UNBOUNDED FOLLOWING and it reports the true last row.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.