Sort NULL values to the end of a table

SqlPostgresqlNullSql Order-By

Sql Problem Overview


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

Sql Solutions


Solution 1 - Sql

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 - Sql

Does this make the trick?

ORDER BY somevalue DESC NULLS LAST

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhelleView Question on Stackoverflow
Solution 1 - SqlErwin BrandstetterView Answer on Stackoverflow
Solution 2 - SqlMosty MostachoView Answer on Stackoverflow