I want to select max Id from nested select.
Here is the my query:
select max(Id) from (SELECT TOP 100 Id FROM [MyTable]) t
This select should return 100, but it actually returns max id of MyTable.
P.S. MyTable contains 100 000 records, so query returns 100 000.
Here is an Example:
returns 100 (It’s ok)
SELECT TOP 100 Id FROM [MyTable]
returns 100 000, but I want to select max id of “SELECT TOP 100 Id FROM [MyTable]”
select max(Id) from (SELECT TOP 100 Id FROM [MyTable]) t
returns 100 000, but I want to select max id of “SELECT TOP 100 Id FROM [MyTable] where Id > 100”
select max(Id) from (SELECT TOP 100 Id FROM [MyTable] where Id > 100) t
Queries with
TOPbut withoutORDER BY, like yours:do not return consistent results. The above means “show me 100 IDs, I don’t care which, from the millions there are in the table”. The DBMS is free to return any 100 it chooses, any time you run the query. It can even choose to send you back the same 100 for the first 2 years, then suddenly change its mind and return some other 100 of them.
In fact, that’s what you see, when it is used a subquery, the optimizer transforms the query “give me the max of any 100 IDs” to “give me the max of all the IDs of the table”
Change that query to (you can use any
ORDER BYof your choice):on its own and where it is used as a subquery and you will have consistent behaviour.