I want to reverse the order in SQL Server of results after using desc. For example:
SELECT TOP 3 * FROM table ORDER BY id DESC
returns results:
505 504 503
But then I want to flip the results to look like this:
503 504 505
I tried
SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) ORDER BY id ASC
But that did not work. How can I fix it?
ASCending and DESCending Order Direction By default things are sorted by ascending order. You can choose to reverse that order by specifying DESC, for descending. Similarly if you'd like to specify that you want ASCending you use ASC.
The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.
You can use the ASC and DESC keywords to specify ascending (smallest value first) or descending (largest value first) order. The default order is ascending.
When sorting your result set in descending order, you use the DESC attribute in your ORDER BY clause. For example: SELECT last_name FROM employees WHERE first_name = 'Sarah' ORDER BY last_name DESC; This SQL Server ORDER BY example would return all records sorted by the last_name field in descending order.
That should work as long as you alias the subquery.
SELECT q.* FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) q ORDER BY q.id ASC
I think you forgot the subselect alias
SELECT * FROM ( SELECT TOP 3 * FROM table ORDER BY id DESC ) s ORDER BY id ASC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With