Overcoming the Absence of NULL Sorting in Descending Order
In PostgreSQL, sorting rows with NULL values to the end of a table can be challenging when using descending order.
Default Behavior
By default, NULL values are sorted to the end of the table in ascending order. However, when sorting in descending order, the inverse occurs, and NULL values appear at the beginning of the results.
NULLS LAST for PostgreSQL 8.3
PostgreSQL 8.3 introduced the NULLS LAST clause, which allows you to explicitly specify that NULL values should be sorted last in descending order. The syntax is:
ORDER BY somevalue DESC NULLS LAST
Alternative Method for Older Versions
For earlier versions of PostgreSQL or other RDBMS without standard SQL NULLS LAST syntax, you can use the following workaround:
ORDER BY (somevalue IS NULL), somevalue DESC
Since FALSE sorts before TRUE, NULL values (evaluated as FALSE) will be sorted last in descending order.
The above is the detailed content of How Can I Sort NULL Values Last in Descending Order in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!