Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CASE Statement for Order By Clause with Multiple Columns and Desc/Asc Sort

Following on from my earlier question here Case statement for Order By clause with Desc/Asc sort I have a statement like this:

SELECT      * FROM     TableName WHERE ORDER BY      CASE @OrderByColumn WHEN 1 THEN Forename END DESC,      CASE @OrderByColumn WHEN 2 THEN Surname END ASC  

This works well, but sometimes I need more than column in the order by. I actually need something like this:

..... ORDER BY     CASE @OrderByColumn WHEN 1 THEN Forename, Date, Location END DESC 

I can't work out how to make the CASE statement allow multiple columns in the THEN part.

like image 787
volume one Avatar asked Sep 25 '14 22:09

volume one


People also ask

How do I sort multiple columns in ascending order in SQL?

Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first. The column that is entered at first place will get sorted first and likewise.

Can order clause be used for multiple columns?

ORDER BY clause is used to sort the returned records in an order. By using ORDER BY clause, we can sort the result in ascending or descending order. This clause can be used with multiple columns as well.

How do you use a case statement in ORDER BY clause?

How to use CASE with ORDER BY clause in SQL Server? To do this, we use the CASE after ORDER BY and then checks for column value. In above case, all records having Active = 1 is sorted on “Active ASC” order. All records having Active = 0 is sorted on 'LastName DESC' else 'FirstName DESC' order.

How do I sort by both ASC and DESC 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.


1 Answers

You can write multiple cases, even if they all have the same condition.

ORDER BY      CASE @OrderByColumn WHEN 1 THEN Forename END DESC,      CASE @OrderByColumn WHEN 1 THEN Date END,      CASE @OrderByColumn WHEN 1 THEN Location END,      CASE @OrderByColumn WHEN 2 THEN Surname END ASC  

Actually, you don't specify a column to sort by, but an expression.

The case statement returns null if the condition is not met, so actually it means:

CASE @OrderByColumn WHEN 1 THEN Forename ELSE NULL END 

So if @OrderByColumn is not 1 then the statement returns always NULL. That doesn't exclude it from sorting, by the way, but it puts all those rows together in the result, making 'SurName' the decisive sorting within that group of rows.

like image 131
GolezTrol Avatar answered Sep 24 '22 10:09

GolezTrol