SQL Windowing Functions: Are the results ordered

order-bywindow functions

If I have a window function which uses something like

SELECT *, row_number() OVER (ORDER BY something) FROM table

should the results be ordered?

I am currently testing out my queries in Microsoft SQL Server, and it certainly seems to be ordered, but I know that this product has the tendency to order rows when it hasn’t been asked.

Is this the standard behaviour?

Best Answer

Without a presentation ORDER BY clause, standard behavior returns a set in no particular order.

I think Itzik Ben-Gan explains it best and even without one of his books, you can find the explanation in this article. About 12 paragraphs down, next to the first code sample, the text describes how the ORDER BY in the window function serves a logical function to describe the set, and how that is completely separate from a presentation ORDER BY clause.

A related question appears here Is SELECT ROW_NUMBER() guaranteed to return results sorted by the generated row numbers?