Sort NULL values to the end of a table

47,112

Solution 1

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 on top.
PostgreSQL 8.3 introduced NULLS LAST:

ORDER BY somevalue DESC NULLS LAST

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

ORDER BY (somevalue IS NULL), somevalue DESC

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

See:

Solution 2

Does this make the trick?

ORDER BY somevalue DESC NULLS LAST

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

Share:
47,112

Related videos on Youtube

helle
Author by

helle

Austrian Software Engineer based in Vienna. Always looking for a new challenge...

Updated on July 11, 2022

Comments

  • helle
    helle almost 2 years

    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 BY somevalue, PUT_NULL_TO_END
    
  • Christophe Roussy
    Christophe Roussy over 5 years
    IMHO in most real world applications you would want null values last whatever the order. For example sorting DESC on an optional timestamp, firstname, lastname, ... so I find it really suspect even though it seems to make sense that mathematically DESC order is the opposite of ASC. Maybe the nulls are just to be in a category of their own and should not be affected by ASC, DESC and always put last, that would have been a better default.
  • Christophe Roussy
    Christophe Roussy over 5 years
    It could affect the indexes if they are DESC maybe you could add a note about that too ? postgresql.org/message-id/…
  • Erwin Brandstetter
    Erwin Brandstetter over 5 years
    @ChristopheRoussy: Indexes matching the sort order are touched in the linked answer above.
  • Stephen
    Stephen about 5 years
    Personally I think the default should have been the opposite: NULLs come first in ascending order, and last in descending order. That's much more intuitive, as NULL is the "smallest" value.
  • CodeGuru
    CodeGuru over 4 years
    For people coming from MYSQL , this is a lol? Why was it built like this in the first place. OR did Mysql over optimize the result