ORDER BY ASC with Nulls at the Bottom

℡╲_俬逩灬. 提交于 2019-11-27 13:26:25

Only 1 minute after asking the question I found my answer. In the order by clause use case to make nulls have a higher value than anything else:

 ORDER BY (CASE WHEN districts.id IS NULL then 1 ELSE 0 END),districts.name, schools.name;

You could use the ISNULL() function.

From the MySQL manual:

ISNULL(expr)

If expr is NULL, ISNULL() returns 1, otherwise it returns 0.

For example:

ORDER BY ISNULL(districts.name), districts.name, schools.name

I like to use this instead of the CASE option for MySQL. Just be aware that it's not portable since ISNULL() is not standard SQL and functions differently in other versions of SQL.

Nulls by default occur at the top, but you can use IsNull to assign default values, that will put it in the position you require...


SELECT schools.id AS schoolid,schools.name AS school, districts.id AS districtid, districts.name AS district FROM sms_schools AS schools LEFT JOIN sms_districts AS districts ON schools.districtid = districts.id WHERE 1 = 1 
ORDER BY isnull(districts.name,'1'), schools.name 

SELECT
 schools.id AS schoolid,
 schools.name AS school,
 districts.id AS districtid,
 districts.name AS district,
 if(schools.districtid IS NULL,1,0) as sort 
FROM sms_schools AS schools
LEFT JOIN sms_districts AS districts 
 ON schools.districtid = districts.id
WHERE 1 = 1
ORDER BY sort, districts.name, schools.name

put any more sort rules insite the 'new' colunm and use any number hide the field in your code, test if it is possebele to sort on the if dirctly(order by if...)

good luck

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