How to order by certain part of a string, assuming i have column codes
which has values of the following format: LLL_NNN, example dGd_542. How can i order by the second part of the string which is numerical?
You should be able to just extract substring from your code.
order by SUBSTRING(codes, 4) asc
use the SUBSTRING
function
SELECT * FROM tablename
ORDER BY SUBSTRING(codes FROM 4)
On very large tables this can lead to performance issues.
(First the obligatory comment on database structure)
It appears the you have two meaningful values encoded into the single column codes
. If at all possible you should refactor your database so those are separate columns. The sorting problem then goes away.
(Now the answer using the existing database structure)
You can use an expression and order by that expression:
SELECT c1, c2, c3, SUBSTRING_INDEX(codes, '_', 2) as code_value
FROM table ORDER BY code_value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With