

When using PARTITION BY
and ORDER BY
in SQL window functions, the order of these clauses inside the OVER()
is very important—and here's why:
LAG(age) OVER (PARTITION BY country ORDER BY age)
PARTITION BY
comes first because it splits the data into groups (partitions) based on the specified column (in this case,country
).
Think of it like creating smaller, isolated "mini-tables" within your result set for each country.ORDER BY
comes after, because once the data is partitioned, you need to define the order within each partition.
Functions likeLAG
andLEAD
depend on the order to know which previous or next row to reference.
Now, your code doesn't run because you have placed ORDER BY
first before PARTITION BY
. However, SQL needs to know the groups before it can order within those groups.
Hope this helps!