Friday, April 29, 2011

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:

SELECT * FROM Data ORDER BY SortOrder CASE WHEN @Direction = 1 THEN DESC END
From stackoverflow
  • I have done something like this

    select productId, InventoryCount, 
        case 
        when @Direction = 1 then InventoryCount 
        else -InventoryCount 
        end as "SortOrder"
    order by 3
    
    Shimmy : I don't understand what you wrote, anyway, I edited my query in the question please review the query.
    MikeW : My answer is essentially the same as the accepted answer, except his is better, having the logic entirely in the ORDER BY clause, where I've included a dummy column and ordered on that.
  • Don't change the ASC or DESC, change the sign of the thing being sorted-by:

    SELECT * FROM table 
    ORDER BY 
    CASE WHEN @Direction = 1 THEN -id else id END asc;
    

    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:

    SELECT * FROM table 
    ORDER BY 
    CASE WHEN @Direction = 1 THEN -id else id END 
    CASE WHEN @Direction = 1 THEN -othercolumn else othercolumn END ;
    

    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.

    Shimmy : Guys, I am not the SQL Expert, please explain me what means the id and -id, does it controls the ordering direction?
    Shimmy : Also, I have edited my query, please review it.
    Shimmy : So I actually don't have to write ASC, Right?
    tpdi : Right, asc is the default.
  • SELECT * 
    FROM Data 
    ORDER BY 
    Case WHEN @Direction = 1 THEN SortOrder END DESC, 
    Case WHEN 1=1 THEN SortOrder END
    

0 comments:

Post a Comment