Example 1
Compute year-over-year revenue growth for three consecutive fiscal years
The CTE computes LAG(revenue) once and names the result prev_revenue, keeping the outer query readable. The 2022 row has no prior year so prev_revenue and yoy_growth_pct are both NULL. For 2023: (1200 − 1000) × 100.0 / 1000 = 20.0%. For 2024: (1500 − 1200) × 100.0 / 1200 = 25.0%. Using 100.0 instead of 100 forces decimal division so the result is never truncated to an integer. ROUND(..., 1) limits the output to one decimal place. To handle the NULL first row gracefully in a report, wrap yoy_growth_pct in COALESCE(yoy_growth_pct, 0) or display it as 'N/A' via a CASE expression.
CREATE TABLE annual_revenue (fiscal_year INT, revenue INT);
INSERT INTO
annual_revenue
VALUES
(2022, 1000),
(2023, 1200),
(2024, 1500);WITH
prev AS (
SELECT
fiscal_year,
revenue,
LAG (revenue) OVER (
ORDER BY
fiscal_year
) AS prev_revenue
FROM
annual_revenue
)
SELECT
fiscal_year,
revenue,
prev_revenue,
ROUND(
(revenue - prev_revenue) * 100.0 / prev_revenue,
1
) AS yoy_growth_pct
FROM
prev
ORDER BY
fiscal_year;| fiscal_year | revenue | prev_revenue | yoy_growth_pct |
|---|---|---|---|
| 2022 | 1000 | NULL | NULL |
| 2023 | 1200 | 1000 | 20 |
| 2024 | 1500 | 1200 | 25 |
Output is identical across all supported engine versions.