I am using SQL Server 2014 and trying to get 10th record and wrote following query.
SELECT TOP 1 *
FROM (SELECT TOP 10 * from Books) AS B
ORDER BY ID DESC;
But it returns me the the last record. I figure out that it is using order by ID DESC from outer query.
Few more tries and its results are as below.
Query 1 Its working as expected.
SELECT *
FROM (SELECT TOP 10 * from Books) AS B
Query 2 Its not working as expected. It should be return records with ID from 10-1.
SELECT *
FROM (SELECT TOP 10 * from Books) AS B
ORDER BY ID DESC;
Query 3 If I'm using ORDER BY
inside subquery then it's working as expected.
SELECT *
FROM (SELECT TOP 10 * from Books ORDER BY ID ASC) AS B
ORDER BY ID DESC;
Can anyone tell me what I'm doing wrong. Why it is necessary to use ORDER BY
inside subquery?
If in Query 1 getting records from ID between 1-10 then why in Query 2 it returns last 10 records? I have just added ORDER BY DESC which should re-order fetched records from subquery only.?
Also tried on W3School Try it yourself link here with following query and its working properly.
SELECT TOP 1 * FROM (SELECT TOP 10 * from Customers) AS B ORDER BY CustomerId DESC;