Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by certain part of a string?

Tags:

sql

mysql

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?

like image 720
Babiker Avatar asked Jan 24 '11 18:01

Babiker


3 Answers

You should be able to just extract substring from your code.

order by SUBSTRING(codes, 4) asc
like image 90
Nikita Rybak Avatar answered Sep 30 '22 06:09

Nikita Rybak


use the SUBSTRING function

SELECT * FROM tablename
ORDER BY SUBSTRING(codes FROM 4)

On very large tables this can lead to performance issues.

like image 24
Matten Avatar answered Sep 30 '22 04:09

Matten


(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
like image 44
Larry Lustig Avatar answered Sep 30 '22 05:09

Larry Lustig