The field empcode is having a data type corresponding to characters.
Here, LAMO1 is less than LAMO2 and so on, but observe that the string is compared character by character. Therefore, LAMO10 is smaller than LAMO2 because while comparing from the left, the first 4 characters LAMO are equal, the 5th character 1 in LAMO10 is smaller than the 5th character 2 in LAMO2. So, the order that you would get (if you removed the limit in your query) is:
This explains why you aren’t getting your desired output LAMO10. To generate it, you need to order by only the numbers in your string. In this particular dataset, that number you are looking for appears to be everything onward from the 5th character. The corresponding query segment for ordering would be:
ORDER BY CAST(SUBSTR(empcode,5) AS UNSIGNED) DESC
So, putting it in your query:
SELECT empcode
FROM employee
WHERE empcode like 'LAMO%'
ORDER BY CAST(SUBSTR(empcode,5) AS UNSIGNED) DESC
LIMIT 1;
2
Answers
You may use an order by clause which sorts on the numeric component of the employee code:
The field
empcode
is having a data type corresponding to characters.Here, LAMO1 is less than LAMO2 and so on, but observe that the string is compared character by character. Therefore, LAMO10 is smaller than LAMO2 because while comparing from the left, the first 4 characters
LAMO
are equal, the 5th character1
in LAMO10 is smaller than the 5th character2
in LAMO2. So, the order that you would get (if you removed thelimit
in your query) is:This explains why you aren’t getting your desired output
LAMO10
. To generate it, you need to order by only the numbers in your string. In this particular dataset, that number you are looking for appears to be everything onward from the 5th character. The corresponding query segment for ordering would be:So, putting it in your query:
should get you your desired result.