Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional SQL ORDER BY ASC/DESC for alpha columns

Writing a stored procedure in MS SQL Server 2008 R2, I want to avoid using DSQL...

I would like the sort method (ASC or DESC) to be conditional.

Now, with a numeric column I would simply use a case statement and negate the value to emulate ASC or DESC... That is:

... ORDER BY CASE @OrderAscOrDesc WHEN 0 THEN [NumericColumn] ELSE -[NumericColumn] END ASC

What is an appropriate method for doing this with an alpha column?

EDIT: I thought of a clever way but it seems terribly inefficient... I could insert my ordered alpha column into a temp table with an autonumber then sort by the autonumber using the method described above.

EDIT2:

What do you guys think of this approach?

ORDER BY CASE @OrderAscOrDesc WHEN 0 THEN [AlphaColumn] ELSE '' END ASC,
CASE @OrderAscOrDesc WHEN 0 THEN '' ELSE [AlphaColumn] END DESC

I don't know if forcing a sort on a uniform column is more efficient than deriving numbers from sorted strings though

like image 969
Matthew Avatar asked Oct 07 '10 18:10

Matthew


People also ask

How do I sort by both ASC and DESC in SQL?

If you want to sort some of the data in ascending order and other data in descending order, then you would have to use the ASC and DESC keywords. SELECT * FROM table ORDER BY column1 ASC, column2 DESC; That is how to use the ORDER BY clause in SQL to sort data in ascending order.

How do you apply condition in order?

SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list.

How do I arrange names in ascending order in SQL?

The SQL ORDER BY Keyword 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 you use a case in ORDER BY clause?

CASE Syntax: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN condition3 THEN result3 ELSE result END; ORDER BY: This keyword is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default.


1 Answers

One option

;WITH cQuery AS
(
   SELECT
       *,
       ROW_NUMBER() OVER (ORDER BY SortColumn) AS RowNum
   FROM
       MyTable
)
SELECT
   *
FROM
   cQuery
ORDER BY
   RowNum * @Direction --1 = ASC or -1 = DESC

Or CASE which IMHO is a bit uglier

ORDER BY
  CASE WHEN 'ASC' THEN SortColumn ELSE '' END ASC,
  CASE WHEN 'DESC' THEN SortColumn ELSE '' END DESC
like image 166
gbn Avatar answered Oct 10 '22 08:10

gbn