- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements