Fetch substrings from a string with words separated by slash in MySQL?


For this, you can use SUBSTRING_INDEX(). Let us first create a −

mysql> create table DemoTable1416
   -> (
   -> StudentCode varchar(100)
   -> );
Query OK, 0 rows affected (1.56 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1416 values('101/John/Smith');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1416 values('901/Carol/Taylor');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1416 values('400/David/Miller');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select −

mysql> select * from DemoTable1416;

This will produce the following output −

+------------------+
| StudentCode      |
+------------------+
| 101/John/Smith   |
| 901/Carol/Taylor |
| 400/David/Miller |
+------------------+
3 rows in set (0.00 sec)

Following is the query to fetch substrings from a string with words separated by slash −

mysql> select substring_index(StudentCode,'/',-2) from DemoTable1416;

This will produce the following output −

+-------------------------------------+
| substring_index(StudentCode,'/',-2) |
+-------------------------------------+
| John/Smith                          |
| Carol/Taylor                        |
| David/Miller                        |
+-------------------------------------+
3 rows in set (0.00 sec)

Updated on: 12-Nov-2019

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements