How to cut part of a string with a MySQL query?

MySQLMySQLi Database

For this, use substring_index() function from MySQL. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> StudentId varchar(100)
   -> );
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('STU-1011');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('STU-95968686');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------+
| StudentId    |
+--------------+
| STU-1011     |
| STU-95968686 |
+--------------+
2 rows in set (0.00 sec)

Following is the query to cut part of a string in MySQL before hyphen (-) −

mysql> select substring_index(substring(StudentId, instr(StudentId, "-")+1), " ", 1) from DemoTable;

This will produce the following output displaying part of the string before hyphen (-)

+------------------------------------------------------------------------+
| substring_index(substring(StudentId, instr(StudentId, "-")+1), " ", 1) |
+------------------------------------------------------------------------+
| 1011                                                                   |
| 95968686                                                               |
+------------------------------------------------------------------------+
2 rows in set (0.02 sec)
raja
Published on 10-Jul-2019 12:26:07
Advertisements