RandyMcKay
RandyMcKay

Reputation: 326

T-SQL ORDER BY custom sorting

Having IDs in range (-12 to 700, no 0).

I want to output a table sorted by IDs with IDs 1 to 700 coming first and then from -1 to -12.

Avoiding dealing with unions and splitting the sets by >0 and <0, is there a way to sort it like I want?

Upvotes: 0

Views: 43

Answers (1)

Thom A
Thom A

Reputation: 95574

Couple of CASE expressions would do this:

ORDER BY CASE WHEN YourColumn > 0 THEN 1 ELSE 2 END ASC,
         CASE WHEN YourColumn > 0 THEN YourColumn END ASC,
         YourColumn DESC; --As already inferred it is now less than 0

DB<>Fiddle

Upvotes: 5

Related Questions