MySQL - select first word from string using SUBSTR

December 2, 2017 | Category : SQL MySQL

In this small article, i would like to share with you how to extract the first word of string in sql query. i did that using SUBSTR, LOCATE and If statement.

Yesterday, i was working on my laravel project and i require to get first name from fulname column like as example:

"Hardik Savani"

Hardik Savani is a full name but i just need to get first work "Hardik" from fullname of users table in phpmyadmin. So i can consider First name from fullname. So basically here also malke it possibility to if just one word then what should it returns. But i use If for that.

For getting first name i use SUBSTR, LOCATE and If condition, So here i made sql query for getting firstname from fullname column.

SQL Query:

SELECT

id, IF((SUBSTR(fullname, 1, LOCATE(' ' ,fullname))) = '',fullname, (SUBSTR(fullname, 1, LOCATE(' ' ,fullname)))) as firstname

FROM `users`

As write above query, you can simply get first name from fullname.

i hope you found your best solution...