0
votes

I have a SQL query that I'm running with a conditional order by statement.

I'm trying to order by desc with nulls last, however my query returns the results not in asc order.

Here's an example:

DECLARE @Sort varchar(300);
SET @Sort = 'UngradedDescription asc'

SELECT 
    [UngradedDescription]
FROM 
    [dbo].[CardListing_Staging]
ORDER BY
    CASE 
        WHEN @Sort = 'UngradedDescription asc' 
            THEN ((CASE WHEN UngradedDescription IS NULL THEN 1 ELSE 0 END))
    END 

These are the results I get:

enter image description here

How can I get them in asc order 02... 04... 06... nulls?

1

1 Answers

0
votes

After some testing I found out it's multiple case statements

declare @Sort varchar(300);

set @Sort = 'UngradedDescription asc'
SELECT 
[UngradedDescription]
    
FROM [dbo].[CardListing_Staging]
 
order by 
            
CASE 
WHEN @Sort = 'UngradedDescription asc' then ((CASE WHEN UngradedDescription IS NULL THEN 1 ELSE 0 END))
END,
CASE 
WHEN @Sort = 'UngradedDescription asc' then UngradedDescription
END