Question

I have a database field "name" that contains both first name and last name of the user. For Example:

id  name
1   Martha Ron
2   Ryan Knapp
3   John Mithchell
4   Scott Mathews
5   Dean Johns
.....
.....

How can i get all users order by last name?

Note: I can not create a another field in the database as it is a production database.

Was it helpful?

Solution

Try this SUBSTRING_INDEX

SELECT
* FROM `table`
ORDER BY 
 SUBSTRING_INDEX(`name`, ' ', -1);

See fiddle demo

OTHER TIPS

Try this ... ref http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index

SELECT *, SUBSTRING_INDEX(`name`, ' ', -1) as sortname 
from tablename order sortname;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top