Search code examples
phpmysqlcodeigniter

Order by query is returning different ordering


Order by query is returning different ordering, why?

SELECT class FROM table WHERE class != "" ORDER BY class ASC

Result:

411101000010

*411102000010* (err)

411101000000

411101000020

411101000050 

Why?


Solution

  • I assume your class column is varchar so to sort the column class you need to convert it to int by casting it as INT or using this trick ORDER BY ABS(class).

    SELECT class FROM table
    ORDER BY CAST(class AS INT) ASC
    

    Demo

    Notes:

    Use Single quotes class != '' when you dealing with strings. Double quotes generally aren't used in SQL, but it deponds on database you're using(MySQL accept both single and double quotes).

    The default ordering in ORDER BY clause when nothing has been explicitly specified is ASC.so you can omit the order asc since it is the default.