KenSmooth
PRO
2 weeks ago
Kensmoothcountry asked

Why does the placement matter when using PARTITION BY and ORDER BY in a window function, and can you explain why OVER (ORDER BY age PARTITION BY country) doesn’t work?

Sudip Bhandari
Expert
2 weeks ago

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 like LAG and LEAD 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!

SQL
This question was asked as part of the Learn SQL Basics course.