PostgreSQL中排序相关问题
1 问题描述
工作中在对某一个列表进行降序排序时,发现null值跑到了最前面,按照常理,这不是我们想要的效果。故记录此问题。
2 问题分析
PostgreSQL在进行降序排序的时候默认null是最大的,排在最前面。
3 解决方法
PostgreSQL提供了NULLS FIRST
和NULLS LAST
来控制null值排在前面还是后面。
例:
--null值在前
select * from tablename order by id nulls first;
--null值在后
select * from tablename order by id nulls last;
--null在前配合desc使用
select * from tablename order by id desc nulls first;
--null在后配合desc使用
select * from tablename order by id desc nulls last;
举例:
null值在后,先按照count1降序排列,count1相同再按照count2降序排列
order by count1 desc nulls last, count2 desc nulls last;