Sort NULL values to the end of a table

前端 未结 2 1041
囚心锁ツ
囚心锁ツ 2020-12-02 16:15

Is there a way with PostgreSQL to sort rows with NULL values in fields to the end of the selected table?

Like:

SELECT * FROM table ORDER         


        
相关标签:
2条回答
  • 2020-12-02 16:52

    Does this make the trick?

    ORDER BY somevalue DESC NULLS LAST
    

    Taken from: http://www.postgresql.org/docs/9.0/static/sql-select.html

    0 讨论(0)
  • 2020-12-02 16:53

    First of all, NULL values are sorted last in default ascending order. You don't have to do anything extra.

    The issue applies to descending order, which is the perfect inverse and thus sorts NULL values first. The solution @Mosty pointed out was introduced with PostgreSQL 8.3:

    ORDER BY somevalue DESC NULLS LAST
    

    For PostgreSQL 8.2 and older or other RDBMS without this standard SQL feature you can substitute:

    ORDER BY (somevalue IS NULL), somevalue DESC
    

    FALSE sorts before TRUE, so NULL values come last, just like in the example above.

    Related later answer:

    • PostgreSQL sort by datetime asc, null first?
    0 讨论(0)
提交回复
热议问题