Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server reverse order after using desc

Tags:

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?

like image 896
kqlambert Avatar asked Sep 21 '12 16:09

kqlambert


People also ask

How do I reverse an order in SQL?

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.

Can we use ASC and DESC in SQL?

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.

Is ORDER BY DESC or ASC by default?

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.

How do I use DESC in SQL?

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.


2 Answers

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 
like image 115
Joe Stefanelli Avatar answered Apr 05 '23 11:04

Joe Stefanelli


I think you forgot the subselect alias

SELECT *  FROM (     SELECT TOP 3 *      FROM table      ORDER BY id DESC ) s ORDER BY id ASC 
like image 33
Clodoaldo Neto Avatar answered Apr 05 '23 10:04

Clodoaldo Neto