In a PostgreSQL table with an optional sort field, the goal is to sort values as follows:
To achieve this sorting behavior, one approach is to use the following ORDER BY clause:
ORDER BY (sort IS NOT DISTINCT FROM -1), sort
This clause operates as follows:
Consider the provided sample data:
id | f_id | name | sort |
---|---|---|---|
1 | 1 | zeta | -1 |
2 | 1 | alpha | 1 |
3 | 1 | gamma | 3 |
4 | 1 | beta | 2 |
5 | 1 | delta | NULL |
6 | 1 | epsilon | NULL |
Using the provided clause, the items would be sorted as follows:
alpha, beta, gamma, delta, epsilon, zeta
An equivalent alternative to the initial clause is:
ORDER BY (sort IS DISTINCT FROM -1) DESC, sort
This clause produces the same sorting behavior but uses the DESC keyword to sort the (sort IS DISTINCT FROM -1) expression in descending order.
The above is the detailed content of How to Sort Non-Null Values Ascending, then Nulls, with -1 Values Last in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!