Is there a way with PostgreSQL to sort rows with NULL
values in fields to the end of the selected table?
Like:
SELECT * FROM table ORDER BY somevalue, PUT_NULL_TO_END
If you sort a column with NULL values in ascending order, the NULLs will come first. Alternatively, if you add a DESC keyword to get a descending order, NULLs will appear last.
If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.
If the null ordering is not specified then the handling of the null values is: - NULLS LAST if the sort is ASC - NULLS FIRST if the sort is DESC - If neither ascending nor descending order is specified, and the null ordering is also not specified, then both defaults are used and thus the order will be ascending with ...
1 Answer. The correct answer is, option (a): Null values are displayed last in the ascending sequences.
NULL
values are sorted last in default ascending order. You don't have to do anything extra.
The issue applies to descending order, which is the perfect inverse and thus sorts NULL
values on top.
PostgreSQL 8.3 introduced NULLS LAST
:
ORDER BY somevalue DESC NULLS LAST
For PostgreSQL 8.2 and older or other RDBMS without this standard SQL feature:
ORDER BY (somevalue IS NULL), somevalue DESC
FALSE
sorts before TRUE
, so NULL
values come last, just like in the example above.
See:
SELECT
Does this make the trick?
ORDER BY somevalue DESC NULLS LAST
Taken from: http://www.postgresql.org/docs/9.0/static/sql-select.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With