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
Sort NULL values to the end of a table
提问by helle
Is there a way with PostgreSQL to sort rows with NULL
values 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
FALSE
sorts 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