SQL Server ORDER BY clause in a subquery

I encountered a strange error in SQL Server and I want to get some explanation.

When I write ORDER BYin a subquery, for example

SELECT a FROM (SELECT * FROM A ORDER BY a) T

it produces the following error:

The ORDER BY clause is not valid in views, built-in functions, retrieved tables, subqueries, and general table expressions, unless TOP or FOR is also specified XML.

But when I use TOPin a subquery, it works fine

 SELECT a 
 FROM
    (SELECT TOP 1000000 * FROM A ORDER BY a) T

So, does this mean that I can select the top row of rows A instead

SELECT a FROM (SELECT * FROM A ORDER BY a) T

In this case. what is the cause of the error?

+5
source share
1 answer

- - , , -

TOP - , , X - .

+4

All Articles