Lynn Pettis (7/16/2015)
Here is another way to accomplish the task with no need to create a sort column in a CTE.
SET NOCOUNT ON;
DECLARE @TEST_NULL_SORT TABLE (AREA VARCHAR(50) NOT NULL, CATEGORY VARCHAR(50) NULL);
INSERT INTO @TEST_NULL_SORT
VALUES
('Area 1','Category1')
,('Area 1','Category2')
,('Area 1','Category3')
,('Area 2','Category1')
,('Area 2','Category2')
,('Area 2','Category3')
,('Area 1',NULL)
,('Area 1',NULL)
,('Area 1',NULL)
,('Area 2',NULL)
,('Area 2',NULL)
,('Area 2',NULL);
SELECT
SS.AREA
,SS.CATEGORY
FROM @TEST_NULL_SORT SS
ORDER BY
case when SS.CATEGORY is null then 0 else 1 end desc,
SS.AREA
,SS.CATEGORY;
Good catch Lynn, this eliminates the second sort, close to 30% more efficient than my suggestion! Obviously I should have realized that the first sort could not be reused:pinch:
😎