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...
Do you like below Tutorials ?
- CRUD Laravel 7.x and 6.x Example
- Image Upload Laravel 7.x and 6.x Tutorial
- Laravel 7.x and 6.x Delete File from public folder example
- How to delete directory in Laravel 7.x and 6.x?
- How to create directory if not exists in Laravel 7.x and 6.x?
- Laravel 7.x and 6.x get all files in directory example
- Laravel 7.x and 6.x check file exists in folder example
- Ajax Autocomplete Textbox in Laravel 7.x and 6.x Example