Pgsql排序让空值NULL排在数字后边

遇到一种情况,对数字进行排序的时候,出现NULL在数字后面的情况,现在的需求是NULL排在前面然后才是升序的排数字

【Oracle 结论】 
order by colum asc 时,null默认被放在最后
order by colum desc 时,null默认被放在最前
nulls first 时,强制null放在最前,不为null的按声明顺序[asc|desc]进行排序
nulls last 时,强制null放在最后,不为null的按声明顺序[asc|desc]进行排序 
【MySql 结论】
order by colum asc 时,null默认被放在最前
order by colum desc 时,null默认被放在最后
ORDER BY IF(ISNULL(update_date),0,1) null被强制放在最前,不为null的按声明顺序[asc|desc]进行排序
ORDER BY IF(ISNULL(update_date),1,0) null被强制放在最后,不为null的按声明顺序[asc|desc]进行排序

针对【oracle】我们就需要使用以下语法:

  1. order by order_col [asc|desc] nulls [first|last]  

而针对【mysql】我们则需要使用以下语法:

  1. order by IF(ISNULL(my_field),1,0),my_field;  
    

下面在oracle11g下做个测试:

测试数据:

rownum create_date update_date
1 20-3月 -11 18-6月 -11
2 20-4月 -11
3 20-5月 -11 20-6月 -11

【无排序/默认排序】

  1. select update_date from table_name ;   
leeyee 写道
[结果]
1 18-6月 -11

3 20-6月 -11

【asc排序】

  1. select update_date from table_name order by update_date;   
leeyee 写道
[结果]
1 20-6月 -11
2 18-6月 -11
3

【desc排序】

  1. select update_date from table_name order by update_date desc;   
leeyee 写道
[结果]

2 18-6月 -11
3 20-6月 -11

【asc排序,强制null放在最前】

  1. select update_date from table_name order by update_date nulls first;   
leeyee 写道
[结果]

2 20-6月 -11
3 18-6月 -11

【asc排序,强制null放在最后】

  1. select update_date from table_name order by update_date nulls last;   
leeyee 写道
[结果]
1 20-6月 -11
2 18-6月 -11
3

mysql5.0测试

 

select update_date from table_name order by IF(ISNULL(update_date),0,1),update_date;   

,同Orcel一样,PGsql也同样适用。

该文转自 http://blog.csdn.net/oxcow/article/details/6554168

原文地址:https://www.cnblogs.com/sunxun/p/6802989.html