Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderBy in SQL Server to put positive values before negative values

I have table in SQL Server which contains a column of type "int". The column can contain positive as well as negative values. I want to carry out sorting based on this column values such that rows with positive values in this column come before the negative values.

Example:

Code SortColumn
A     1
B     5
C    -1
D    -3
E     0
F     2

Desired Output:

Code SortColumn
E        0
A        1
F        2
B        5
C       -3
D       -1
like image 573
Brij Avatar asked Feb 16 '13 07:02

Brij


People also ask

How do I arrange in ascending and descending order in SQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do I make a negative value positive in SQL Server?

We can convert Negative amount to Positive Amount using ABS() function.

Can we use 2 order by in SQL?

If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY . This clause comes at the end of your SQL query.

Does order matter in the FROM clause in SQL?

No, that order doesn't matter (or at least: shouldn't matter). Any decent query optimizer will look at all the parts of the WHERE clause and figure out the most efficient way to satisfy that query.


1 Answers

Select * from Table
order by 
Case when sortcolumn<0 then 1 else 0 end
,sortcolumn
like image 127
bummi Avatar answered Oct 22 '22 21:10

bummi