Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the result set ordering when using window functions that have `order by` components?

I'm working on a query on the SEDE:

select top 20 
  row_number() over(order by "percentage approved" desc, approved desc), 
  row_number() over(order by "total edits" asc), 
  *
from editors 
where "total edits" > 30

What is the ordering of the result set, taking into account the two window functions?

I suspect it's undefined but couldn't find a definitive answer. OTOH, results from queries with one such window function were ordered according to the over(order by ...) clause.

like image 787
Matt Fenwick Avatar asked Dec 18 '25 23:12

Matt Fenwick


1 Answers

The results can be returned in any order.

Now, they will often be returned in the same order as specified in the OVER clause, but this is just because SQL Server is likely to pick a query plan that sorts the rows to calculate the aggregate. This is by no means guaranteed, as it could pick a different query plan at any time, especially as you make your query more complex which extends the space of possible query plans.

like image 132
Krzysztof Kozielczyk Avatar answered Dec 21 '25 15:12

Krzysztof Kozielczyk