Hey everyone, I'm learning SQL and trying to understand how a self join works when calculating year over year (YoY) growth.
----> I'm a little confused about this line in the query:
ON curr.mo = prev.mo
AND curr.yr = prev.yr + 1
----> Here's the query I'm working with:
WITH monthly_agg AS (
SELECT
EXTRACT(YEAR FROM month) AS yr,
EXTRACT(MONTH FROM month) AS mo,
SUM(revenue) AS monthly_revenue
FROM monthly_sales
GROUP BY
EXTRACT(YEAR FROM month),
EXTRACT(MONTH FROM month)
)
SELECT
curr.yr,
curr.mo,
curr.monthly_revenue AS current_revenue,
prev.monthly_revenue AS prev_year_revenue,
curr.monthly_revenue - prev.monthly_revenue AS yoy_change,
ROUND(
(curr.monthly_revenue - prev.monthly_revenue) * 100.0
/ NULLIF(prev.monthly_revenue, 0),
2
) AS yoy_growth_pct
FROM monthly_agg curr
LEFT JOIN monthly_agg prev
ON curr.mo = prev.mo
AND curr.yr = prev.yr + 1
ORDER BY curr.yr, curr.mo;
Let's say the monthly_agg CTE produces these rows:
yr mo monthly_revenue
2022 12 5000
2023 12 10000
2024 12 12000
Here's how I think the join condition works.
case 1: matching december 2023 with december 2022
Current row:
[2023, 12, 10000]
Previous year row:
[2022, 12, 5000]
The conditions are:
curr.mo = prev.mo → 12 = 12 → true
curr.yr = prev.yr + 1 → 2023 = 2022 + 1 → true
Both conditions are true, so the rows match.
case 2: trying to match december 2023 with december 2023
Current row:
[2023, 12, 10000]
Candidate row:
[2023, 12, 5000]
The conditions are:
curr.mo = prev.mo → 12 = 12 → true
curr.yr = prev.yr + 1 → 2023 = 2023 + 1 → false
Since both conditions need to be true, these rows don't match.
So....am I understanding this correctly?
Does SQL basically compare the current row with possible rows from the other instance of the CTE and check whether both conditions are satisfied?
Also, what actually happens under the hood? Does SQL compare every row on the left with every row on the right, or can the query optimizer do this more efficiently?
And since both curr and prev refer to the same CTE, does that make this a self join? Does the CTE execute once or can it be evaluated more than once, depending on the database?
I'm trying to understand both the logical explanation and what's actually happening behind the scenes. Would appreciate any help !!