简体   繁体   中英

Does ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) preserves the order?

I am planning to use ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) in select queries which do not have the any proper data columns to use in order-by clause.

Generally, ROW_NUMBER() will be ordered exactly the same with each execution if I use ORDER BY with valid column data. By using ORDER BY (SELECT NULL) , what will be ROW_NUMBER() order, will it change with each execution?

If order is not changing (tested from my side, order is not changing), is it good use?

Without an explicit ORDER BY clause you may get different ROW_NUMBER() for a specific row on different executions. Same with ORDER BY (SELECT NULL) which is either a hack to bypass the syntax requirements or a syntactic sugar; it does not enforce an order.

You are getting same results, yes, but there is no guarantee .

You have tagged with question MySQL. But you have used unnecessarily arcane syntax. MySQL supports both these constructs:

ROW_NUMBER() OVER ()
ROW_NUMBER() OVER (ORDER BY NULL)

In both cases, you are saying "I don't care what the order is". A very important corollary: "I don't care if the result is the same on two different runs of the same query.

To be honest, ROW_NUMBER() is not guaranteed to return the same result when the ORDER BY keys are the same. Why? Because SQL tables and result sets represent unordered sets. There is no "default" ordering to fall back on.

Your particular syntax is a work-around for SQL Server, because that database requires an ORDER BY clause for ROW_NUMBER() and SQL Server does not allow constants in the ORDER BY .

Of course, exactly the same conditions hold in that database -- or in any other database.

The simple answer is: No, you cannot assume the result will be in the same order if you run the same query again.

执行 ORDER BY (SELECT NULL) 总是返回与执行普通表相同的顺序。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM