I’ve got a query that can spit out results sorted by a variety of columns, but I need to be able to handle null values in the sorted columns. Any help would be greatly appreciated. Here is an example:
Table [People]
Columns [Name], [Birthday] (NULLABLE)
Query where @Sort is an int designating which column to sort on, and @pageStart and @pageEnd are ints telling the query which results to return. (I am returning only a selection of the rows, so I am using a [RowNum] column nested in a CTE. There is also other processing happening, but I’m removing it for simplicity.):
;with results as(
SELECT [Name], [Birthday], ROW_NUMBER() OVER (ORDER BY
CASE WHEN @Sort = 0 THEN [Name] END,
CASE WHEN @Sort = 2 THEN [Birthday] END,
CASE WHEN @Sort = 1 THEN [Name] END DESC,
CASE WHEN @Sort = 3 THEN [Birthday] END DESC) AS RowNum
FROM [People]
)
SELECT [Name], [Birthday]
FROM results
WHERE RowNum BETWEEN @pageStart AND @pageEnd
--ORDER RowNum
--The last order by doesn't seem to be needed
I know that nulls can be handled with a statement such as:
ORDER BY (CASE WHEN [columnName] is NULL THEN 1 ELSE 0 END), [columnName]
I’m having a hard time applying that to the query I am working with… any help would be greatly appreciated! Let me know if I can clarify anything.
It seems like you’re mostly there. Instead of a
CASE...WHEN...ENDstatement you could instead useISNULL()You’ll need to choose relevant values from the same datatype, but for
@Sort = 0for example you could useIt also looks like you could condense you sequence of
CASE...WHEN...ENDstatements into one more like