Skip to content
Advertisement

MS Sql: Conditional ORDER BY ASC/DESC Question

I want to to make to make the ordering in my query conditional so if it satisfiess the condition it should be ordered by descending

For instance:

Advertisement

Answer

Don’t change the ASC or DESC, change the sign of the thing being sorted-by:

The OP asks:

Guys, I am not the SQL Expert, please explain me what means the id and -id, does it controls the ordering direction?

id is just whatever column you’re sorting by; -id is just the negation of that, id * -1. If you’re sorting by more than one column, you’ll need to negate each column:

If you’re ordering by a non numeric column, you’ll need to find an expression that makes that column “negative”; writing a function to do that may help.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement