Sort NULL values to the end of a table

丶灬走出姿态 提交于 2019-11-28 17:18: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 BY somevalue, PUT_NULL_TO_END

回答1:


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?



回答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



来源:https://stackoverflow.com/questions/7621205/sort-null-values-to-the-end-of-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!