MSQL sort null and empty strings

MSQL sort null and empty strings

 

      NULL sort

SELECT * FROM table
ORDER BY field IS NULL, field;

       In MSQL, null is the smallest by default, so in ascending order, when the field value is null, the null will be listed on the top. If you want to sort the null at the bottom, you can use

ORDER BY field IS NULL, field

 

      In MySQL, IS NULL judges that it is NULL and returns 1, not NULL, and returns 0, so if the field is null in order by, it returns 1, and it returns 0 if it is not null, so that the null value will be listed below in ascending order.

 

      empty string sort

select field
from table
order by case when ifnull(field,'')='' then 0 else 1 end desc, field asc;

      MYSQL IFNULL(expr1,expr2)       

  
      IFNULL() returns expr1 if expr1 is not NULL, otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326802520&siteId=291194637