question

bonskijr avatar image
bonskijr asked

How does the Query Engine know how to order via newid()

While we all know how to display a result in random order via newid() function, I wonder how the query engine interprets a GUID(result of newid), since ORDER BY statement expects a column list (or position)?

NOTE: And if the GUID somehow magically is converted to column position, this assumption is invalid for a table with single column, since it will return results in random order.

Thanks

t-sqlquery
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Håkan Winther avatar image
Håkan Winther answered

As you can see in the text from books online (bold text), order by expression can include an expression. NEWID() that is nondetermanistic is executed for every row returned by your select and then order by is applied on your set of data,

order_by_expression
Specifies a column on which to sort. A sort column can be specified as a name or column alias, or a nonnegative integer representing the position of the name or alias in the select list. An integer cannot be specified when the order_by_expression appears in a ranking function. A sort column can include an expression, but when the database is in SQL Server (90) compatibility mode, the expression cannot resolve to a constant. Column names and aliases can be qualified by the table or view name. In SQL Server, qualified column names and aliases are resolved to columns listed in the FROM clause. If order_by_expression is not qualified, the value must be unique among all columns listed in the SELECT statement.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.