SQL Server equivalent to Oracle's NULLS FIRST?

前端 未结 8 576
心在旅途
心在旅途 2020-12-08 00:50

So Oracle has NULLS FIRST, which I can use to have null values sorted at the top followed by my column value in descending order:

ORDER BY date_sent NULLS FI         


        
相关标签:
8条回答
  • 2020-12-08 00:59
    ORDER BY
      COALESCE(POSTING_DATE,'1900-01-01 00:00:00.000')
     ,OTHER_FIELDS
    
    0 讨论(0)
  • 2020-12-08 01:02

    You can't control this, to my knowledge. And it looks like you have the correct approach with ISNULL.

    With strings, I've used ISNULL(field, '') for the same purpose.

    0 讨论(0)
  • 2020-12-08 01:03

    You can do some trick:

    ORDER BY (CASE WHEN [Order] IS NULL THEN 0 ELSE 1 END), [Order] 
    
    0 讨论(0)
  • 2020-12-08 01:08

    Use Case/When statement, for example:

    ORDER BY (case WHEN ColINT IS NULL THEN {maxIntValue} ELSE ColINT END) DESC
    
    ORDER BY (case WHEN ColVChar IS NULL THEN {maxVCharValue} ELSE ColVChar END) DESC
    
    ORDER BY (case WHEN ColDateT IS NULL THEN {maxDateTValue} ELSE ColDateT END) DESC
    

    ...and so on.

    or even better as you don't care what is your column type and the max value.

    ORDER BY (case WHEN ColAnyType IS NULL THEN 1 ELSE 0 END) DESC, ColAnyType DESC
    
    0 讨论(0)
  • 2020-12-08 01:09

    The quick answer is this: the best solution for changing the ordering of nulls in the necessary cases is the accepted one. But you only have to use it, or a variation of it in the necessary cases:

    • DESC + NULLS FIRST:

      ORDER BY (CASE WHEN [Order] IS NULL THEN 0 ELSE 1 END), [Order] DESC

    • ASC + NULLS LAST:

      ORDER BY (CASE WHEN [Order] IS NULL THEN 1 ELSE 0 END), [Order] ASC

    • ASC + NULLS FIRST: it works fine by default

    • DESC + NULLS LAST: it works fine by default

    Let's see why:

    If you check the ORDER BY Clause (Transact-SQL) MSDN docs, and scroll down to ASC | DESC, you can read this:

    ASC | DESC

    Specifies that the values in the specified column should be sorted in ascending or descending order. ASC sorts from the lowest value to highest value. DESC sorts from highest value to lowest value. ASC is the default sort order. Null values are treated as the lowest possible values.

    So, by default if you specify ASC order, it works like NULLS FIRST. And, if you specify DESC, it works like NULLS LAST.

    So you only need to do change the behavior for NULLS FIRST in DESC order, and for NULLS LAST in ASC order.

    IMHO, the best solution for changing the ordering of nulls in the necessary cases is the accepted one, but I've included it adapted to the different cases in the beginning of my answer.

    0 讨论(0)
  • 2020-12-08 01:14

    This is an alternative way when you want to adjust how nulls appear in the sort order. Negate the column and reverse your sort order. Unfortunately you would need to CAST dateTime columns.

    ORDER BY -CAST(date_sent as int) ASC
    
    0 讨论(0)
提交回复
热议问题