Search code examples
mysqlsql-order-bywhere-clausesql-like

ORDER BY not working in MySQL 5.1


I have a problem with sql query in php:

select
    user, name, outlet, switch, port, vlan, mac, status
from access where 
    user like '%'
    and name like '%'
    and outlet like '%'
    and switch like '%'
    and port like '%'
    and vlan like '%'
    and mac like '%'
    and status like '%'
order by 'user';

When running query on MySQL client version: 5.1.36 query doesn't work totally (ORDER BY won't work), however when running SAME query on MySQL client version: 4.1.13, ORDER BY works!

I have checked nearly all manuals about ORDER BY, WHERE, LIKE commands, but no result. No mention about version differences, etc..


Solution

  • You have to remove the quotes from user in the ORDER BY clause. This is what is causing the ORDER BY not working as expected, because you can use any expression in the ORDER BY clause, and the 'user' in quotes is being considered an expression (constant) instead of a column name.

    Test case (MySQL 5.1.45):

    CREATE TABLE tb (id int);
    
    INSERT INTO tb VALUES (5);
    INSERT INTO tb VALUES (1);
    INSERT INTO tb VALUES (4);
    INSERT INTO tb VALUES (2);
    INSERT INTO tb VALUES (3);
    
    SELECT * FROM tb ORDER BY 'id';
    +------+
    | id   |
    +------+
    |    5 |
    |    1 |
    |    4 |
    |    2 |
    |    3 |
    +------+
    5 rows in set (0.00 sec)
    
    SELECT * FROM tb ORDER BY id;
    +------+
    | id   |
    +------+
    |    1 |
    |    2 |
    |    3 |
    |    4 |
    |    5 |
    +------+
    5 rows in set (0.00 sec)