Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding max in mysql when column is varchar

Tags:

mysql

I have a varchar field that is code of letters and is auto incremented (manualy), so after A is B until after Z becomes AA and so on.

My issue is when I hit AA and I try to select MAX of this field:

SELECT MAX(letter) from jobs

Returns Z instead of AA. This is correct if you are ordering names, but I have a code. There's a way to get this right?

like image 223
Felipe Diesel Avatar asked Feb 20 '11 01:02

Felipe Diesel


2 Answers

Try this one. This will force it to weight longer strings as being higher than shorter strings:

SELECT letter
FROM jobs
ORDER BY LENGTH(letter) DESC, letter DESC
LIMIT 1;

Edit: Yup, forgot to sort DESC to get the MAX...

like image 51
Kevin Stricker Avatar answered Oct 03 '22 08:10

Kevin Stricker


This may help? Sort them by length first, then by letter.

SELECT letter FROM jobs
ORDER BY LENGTH(letter) DESC, letter DESC
LIMIT 0, 1
like image 28
jocull Avatar answered Oct 03 '22 08:10

jocull