SQL ORDER by `no` with NULLs at the end

♀尐吖头ヾ 提交于 2019-11-30 01:27:28

问题


I have got a MySql query that orders me results by no column (int, can be null). Simple example:

SELECT * FROM table ORDER BY no ASC

I would like to get a resultset sorted like

1, 2, 3, 10, 52, 66, NULL, NULL, NULL

but I get

NULL, NULL, NULL, 1, 2, 3, 10, 52, 66

Is it possible with SQL query ?


回答1:


Could you try this?

ORDER BY ISNULL(no),no;



回答2:


You can use a CASE statement to tweak ordering:

SELECT * 
FROM table 
ORDER BY case when no is null then 2 else 1 end, no

This orders on "nullableness" first, and no second.




回答3:


SELECT * FROM table ORDER BY ISNULL(field), field ASC;



回答4:


SELECT * FROM table ORDER BY COALESCE(no,999999) ASC

Just replace the 999999 with something larger if your numbers are naturally bigger than that.




回答5:


Ok, I think I got it:

SELECT * FROM table WHERE no IS NOT NULL ORDER BY no ASC UNION
SELECT * FROM table WHERE no IS NULL

Or is there any better way ?




回答6:


SELECT * FROM table ORDER BY no ASC NULLS LAST



来源:https://stackoverflow.com/questions/1880278/sql-order-by-no-with-nulls-at-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!