SQL 将 NULL 值排序到表的末尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7621205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:18:51  来源:igfitidea点击:

Sort NULL values to the end of a table

sqlpostgresqlnullsql-order-by

提问by helle

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

PostgreSQL 有没有办法将NULL字段中的值的行排序到所选表的末尾?

Like:

喜欢:

SELECT * FROM table ORDER BY somevalue, PUT_NULL_TO_END

回答by Erwin Brandstetter

First of all, NULL values aresorted last in default ascendingorder. You don't have to do anything extra.

首先,NULL值上次在默认排序升序的顺序。你不需要做任何额外的事情。

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

该问题适用于降序,这是完美的逆序,因此首先对 NULL 值进行排序。@Mosty 指出解决方案是在PostgreSQL 8.3中引入的:

ORDER BY somevalue DESC NULLS LAST

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

对于PostgreSQL 8.2及更早版本或其他没有此标准 SQL 功能的 RDBMS,您可以替换:

ORDER BY (somevalue IS NULL), somevalue DESC

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

FALSE排序 before TRUE,所以 NULL 值排在最后,就像上面的例子一样。

Related later answer:

相关后续回答:

回答by Mosty Mostacho

Does this make the trick?

这能解决问题吗?

ORDER BY somevalue DESC NULLS LAST

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

取自:http: //www.postgresql.org/docs/9.0/static/sql-select.html