Lukas Eder explains order of operations in a SQL query:
If you’re not a frequent SQL writer, the syntax can indeed be confusing. Especially
GROUP BY
and aggregations “infect” the rest of the entireSELECT
clause, and things get really weird. When confronted with this weirdness, we have two options:
- Get mad and scream at the SQL language designers
- Accept our fate, close our eyes, forget about the snytax and remember the logicaloperations order
I generally recommend the latter, because then things start making a lot more sense, including the beautiful cumulative daily revenue calculation below, which nests the daily revenue (
SUM(amount)
aggregate function) inside of the cumulative revenue (SUM(...) OVER (...)
window function):
Lukas explains things from an Oracle perspective, so not all of this matches T-SQL, but it’s close enough for comparison.