Split Name String into Two Parts using MySQL SUBSTRING_INDEX Function



To make it understand, we are using the following data from a table named ‘customerdetail’.

mysql> Select * from Customerdetail;
+----------------------+----------------------+-----------+---------------------+
| Name                 | FName                | Address   | Emailid             |
+----------------------+----------------------+-----------+---------------------+
| Advik Jhamb          | Lovkesh Jhamb        | Mumbai    | [email protected]     |
| Chirag Jai Patil     | Raman Jai Patil      | Gujrat    | [email protected]   |
| Devansh Singh Rajput | Kishore Singh Rajput | Rajasthan | [email protected] |
| Mitul Kumar Sharma   | Om Veer Sharma       | Patiala   | [email protected]     |
+----------------------+----------------------+-----------+---------------------+
4 rows in set (0.00 sec)

Now, suppose if we want to split the name into two parts, ‘First_name’ and ‘Last_name’ then it can be done with the help of the following query −

mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 1), ' ', -1) AS First_Name, TRIM( SUBSTR(Name, LOCATE(' ', Name)) ) AS Last_Name FROM Customerdetail;
+------------+--------------+
| First_Name | Last_Name    |
+------------+--------------+
| Advik      | Jhamb        |
| Chirag     | Jai Patil    |
| Devansh    | Singh Rajput |
| Mitul      | Kumar Sharma |
+------------+--------------+
4 rows in set (0.00 sec)

From the result set of above query, it is clear that the name has been divided into two parts. It considers the middle name as a part of the last name.

Updated on: 2020-02-10T07:22:10+05:30

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements