Why do NULL values come first when ordering DESC in a PostgreSQL query?

前端 未结 2 2075
野趣味
野趣味 2020-11-29 12:23

When would you ever want NULLS first when ordering a query descending or ascending?

In my opinion, the vast majority of the time the desired behavio

2条回答
  •  北海茫月
    2020-11-29 13:06

    Actually, with default sort order (ASCENDING) NULL values come last.

    Logic dictates that the sort order be reversed with the DESCENDING keyword, so NULLs come first in this case.

    But the best part comes last: you can choose which way you want it:

    • Use the NULLS FIRST | LAST clause.

    Quoting the current manual, version 9.3 as of writing:

    If NULLS LAST is specified, null values sort after all non-null values; if NULLS FIRST is specified, null values sort before all non-null values. If neither is specified, the default behavior is NULLS LAST when ASC is specified or implied, and NULLS FIRST when DESC is specified (thus, the default is to act as though nulls are larger than non-nulls). When USING is specified, the default nulls ordering depends on whether the operator is a less-than or greater-than operator.

    Bold emphasis mine.

提交回复
热议问题