Skip to content
Advertisement

Using CAST in MYSQL Query, It works in localhost, But in the server not working

In mysql using cast, I wrote the query like

Accnno – varchar

SELECT * FROM books where category = 'Book' ORDER BY CAST(Accnno AS int) DESC LIMIT 0,10

The above query is working fine in the localhost, But is not working in the server, It shows error like

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘int) DESC LIMIT 0,10’ at line 1

Advertisement

Answer

I would suggest using implicit conversion:

SELECT b.*
FROM books b
WHERE b.category = 'Book'
ORDER BY (Accnno + 0) DESC
LIMIT 0, 10;

This will not generate an error. If Accnno does not start with leading zeros and has no decimal places (both of which seem likely), you can also just use string functions:

ORDER BY LENGTH(accnno) DESC, accnno DESC
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement