Get left part of the string on the basis of last occurrence of delimiter in MySQL?


For this, use LEFT() method. For manipulation, we have used the LOCATE() and the REVERSE() method.

Let us first create a table −

mysql> create table DemoTable
(
   Title text
);
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('$/This$is[MySQL]$/MySQL[FirstClass]$MySQL[SecondClass]');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('$/This$is[Java]$/Java[FirstClass]$Java[SecondClass]');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------------------------------------------------+
| Title                                                  |
+--------------------------------------------------------+
| $/This$is[MySQL]$/MySQL[FirstClass]$MySQL[SecondClass] |
| $/This$is[Java]$/Java[FirstClass]$Java[SecondClass]    |
+--------------------------------------------------------+
2 rows in set (0.00 sec)

Following is the query to get left part of the string −

mysql> select left(Title, char_length(Title) - locate('$', reverse(Title))) as result from DemoTable;

This will produce the following output −

+-------------------------------------+
| result                              |
+-------------------------------------+
| $/This$is[MySQL]$/MySQL[FirstClass] |
| $/This$is[Java]$/Java[FirstClass]   |
+-------------------------------------+
2 rows in set (0.04 sec)

Updated on: 07-Oct-2019

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements