Thursday, August 28, 2014

Sorting on Null Values in Oracle

Problem:
You need to find a way to override the sorting of nulls so they appear where you want at the beginning or end of the report.


Solution:
Oracle provides two extensions to the ORDER BY clause to treat NULL values separately from the known data, allowing any NULL entries to sort explicitly to the beginning or end of the results.
select name, p_id
from emp
order by p_id nulls last;

NAME                           P_ID
------------------------------ ---------------
Boris                          1
Rob                            2
Mike                           2
Janene                         5
Janene
Jihny
Robert
Jihn

8 rows selected.

select name, p_id
from emp
order by p_id nulls first;

NAME                           P_ID
------------------------------ ---------------
Jihn
Janene
Jihny
Robert
Boris                          1
Rob                            2
Mike                           2
Janene                         5

8 rows selected.



I hope this helps.

Please feel free to leave your questions or suggest improvements to this section.

No comments:

Post a Comment