Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do window functions and the group by clause interact?

I do understand window functions and group by separately.

But what happens when you use both a window function and a group by clause in the same query ?

  • Are the selected rows grouped first, then considered by the window function ?
  • Or does the window function executes first, then the resulting values are grouped by group by ?
  • Something else ?
like image 345
Benjamin Crouzier Avatar asked May 18 '16 07:05

Benjamin Crouzier


People also ask

Can window function and GROUP BY be used together?

The reason why window functions are not allowed in GROUP BY is the order of operations in SQL. The clauses of a SQL query are processed in a different order than they are written in the query.

Can we use GROUP BY in window function SQL?

Before we start, it is important to note that in terms of the order of operations in SQL, window functions come in sixth on the list. This is important because based off of this logical order, window functions are allowed in SELECT and ORDER BY, but they are not allowed in FROM , WHERE , GROUP BY , or HAVING clauses.

What is the difference between GROUP BY and window functions?

In short and very simplified: window functions retain result row, group by squashes them.

How does a window function work?

Window functions perform calculations on a set of rows that are related together. But, unlike the aggregate functions, windowing functions do not collapse the result of the rows into a single value. Instead, all the rows maintain their original identity and the calculated result is returned for every row.


1 Answers

Quote from the manual:

If the query contains any window functions, these functions are evaluated after any grouping, aggregation, and HAVING filtering is performed

emphasis mine

like image 68
a_horse_with_no_name Avatar answered Sep 28 '22 01:09

a_horse_with_no_name