116

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
Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137
helle
  • 10,634
  • 9
  • 55
  • 82

2 Answers2

217

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:

Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137
  • 2
    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 Oct 24 '18 at 16:38
  • It could affect the indexes if they are DESC maybe you could add a note about that too ? https://www.postgresql.org/message-id/AANLkTinvi12K%3DcK50nLiFSsCGUq3Ven0tLRW_6w2H-3E%40mail.gmail.com – Christophe Roussy Oct 24 '18 at 16:48
  • @ChristopheRoussy: Indexes matching the sort order are touched in the linked answer above. – Erwin Brandstetter Oct 24 '18 at 17:24
  • 4
    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. – Stephen May 24 '19 at 14:04
  • 1
    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 – CodeGuru Nov 19 '19 at 13:21
58

Does this make the trick?

ORDER BY somevalue DESC NULLS LAST

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

Mosty Mostacho
  • 41,294
  • 14
  • 93
  • 121