Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NULL values to the end of a table

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 
like image 709
helle Avatar asked Oct 01 '11 15:10

helle


People also ask

How do I sort by NULLs last in SQL?

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.

How are NULL values sorted?

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.

How do you use NULLs 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 ...

IS NULL values are displayed last in ascending sequences?

1 Answer. The correct answer is, option (a): Null values are displayed last in the ascending sequences.


2 Answers

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:

  • Sort by column ASC, but NULL values first?
  • The manual on SELECT
like image 81
Erwin Brandstetter Avatar answered Nov 15 '22 17:11

Erwin Brandstetter


Does this make the trick?

ORDER BY somevalue DESC NULLS LAST 

Taken from: http://www.postgresql.org/docs/9.0/static/sql-select.html

like image 38
Mosty Mostacho Avatar answered Nov 15 '22 17:11

Mosty Mostacho