Home > Database > Mysql Tutorial > How Can I Sort NULL Values Last in Descending Order in PostgreSQL?

How Can I Sort NULL Values Last in Descending Order in PostgreSQL?

Susan Sarandon
Release: 2024-12-29 20:25:17
Original
920 people have browsed it

How Can I Sort NULL Values Last in Descending Order in PostgreSQL?

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template