Sort by column ASC, but NULL values first?

后端 未结 2 1154
北荒
北荒 2020-11-22 00:55

I need to sort a PostgreSQL table ascending by a date/time field, e.g. last_updated.

But that field is allowed to be empty or null and I want records wi

2条回答
  •  不思量自难忘°
    2020-11-22 01:17

    You can create a custom ORDER BY using a CASE statement.
    The CASE statement checks for your condition and assigns to rows which meet that condition a lower value than that which is assigned to rows which do not meet the condition.
    It's probably easiest to understand given an example:

      SELECT last_updated 
        FROM your_table 
    ORDER BY CASE WHEN last_updated IS NULL THEN 0 ELSE 1 END, 
             last_updated ASC;
    

提交回复
热议问题