Home >Database >Mysql Tutorial >How Does PostgreSQL Handle NULL Value Sorting in Ascending and Descending Orders?

How Does PostgreSQL Handle NULL Value Sorting in Ascending and Descending Orders?

Linda Hamilton
Linda HamiltonOriginal
2024-12-26 00:56:13648browse

How Does PostgreSQL Handle NULL Value Sorting in Ascending and Descending Orders?

Null Value Sorting in PostgreSQL

Postgres handles sorting of NULL values differently depending on the sort order. By default, NULL values are sorted to the end of the table in ascending order. However, sorting in descending order behaves differently.

Descending Order Sorting

In descending order, NULL values are sorted to the top of the table by default. To override this behavior and sort NULL values to the end, PostgreSQL introduced the NULLS LAST keyword in version 8.3:

ORDER BY somevalue DESC NULLS LAST

Pre-PostgreSQL 8.3 and Non-Standard SQL Databases

For PostgreSQL versions 8.2 and earlier, or other RDBMS without the NULLS LAST feature, there is a workaround:

ORDER BY (somevalue IS NULL), somevalue DESC

This sorts NULL values last because FALSE (representing NULL) sorts before TRUE.

The above is the detailed content of How Does PostgreSQL Handle NULL Value Sorting in Ascending and Descending Orders?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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