Most SQL problems that analysts solve with subqueries can be solved in one line.
Window functions do that. Here is how they work.
A window function performs a calculation across a set of rows without collapsing them into a single result the way GROUP BY does.
You keep every row. You just add a new column with the calculated value alongside it.
The syntax is always the same:
function() OVER (PARTITION BY ... ORDER BY ...)
PARTITION BY splits the data into groups.
ORDER BY sets the sequence within each group. Not every window function needs both — but that is the full structure.
Here are the 7 you will actually use:
𝗥𝗢𝗪_𝗡𝗨𝗠𝗕𝗘𝗥 Assigns a unique number to each row. No ties, ever.
𝗥𝗔𝗡𝗞 Ranks rows by value. Tied rows get the same rank and the next number is skipped.
𝗗𝗘𝗡𝗦𝗘_𝗥𝗔𝗡𝗞 Like RANK, but no numbers are skipped after a tie. The sequence stays continuous.
𝗟𝗔𝗚 Pulls the value from the previous row. Use it to compare this period to the last.
𝗟𝗘𝗔𝗗 Pulls the value from the next row. Use it to see what comes after the current row.
𝗥𝗨𝗡𝗡𝗜𝗡𝗚 𝗧𝗢𝗧𝗔𝗟 Adds values cumulatively as it moves through rows in order.
𝗣𝗔𝗥𝗧𝗜𝗧𝗜𝗢𝗡 𝗕𝗬 Resets the calculation for each group. Same idea as GROUP BY, but every individual row stays visible.
The cheatsheet below has the code and output for each one, using the same reference dataset throughout so you can see exactly what changes.
#SQLPerformance #SQL #Database