How to split a column in MySQL?


To split a column, you need to use SUBSTRING_INDEX() in MySQL. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Name varchar(40)
   -> );
Query OK, 0 rows affected (1.80 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John_Smith');
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable values('Carol_Taylor');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values('David_Miller');
Query OK, 1 row affected (0.54 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------+
| Name         |
+--------------+
| John_Smith   |
| Carol_Taylor |
| David_Miller |
+--------------+
3 rows in set (0.00 sec)

Following is the query to split a column in MySQL −

mysql> select if(locate('_',Name)=0,'',substring_index(Name, '_', 1)) from DemoTable;


This will produce the following output:

+---------------------------------------------------------+
| if(locate('_',Name)=0,'',substring_index(Name, '_', 1)) |
+---------------------------------------------------------+
| John                                                    |
| Carol                                                   |
| David                                                   |
+---------------------------------------------------------+
3 rows in set (0.00 sec)

Updated on: 17-Dec-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements