How to get everything before the last occurrence of a character in MySQL?


You can use below syntax. Following is the syntax −

update yourTableName
set yourColumnName=REVERSE(SUBSTRING(REVERSE(yourColumnName),
INSTR(REVERSE(yourColumnName), '.')));

Let us first create a table −

mysql> create table DemoTable
-> (
-> Words text
-> );
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Value1. Value2 .Value3.Value4.Value5');
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+--------------------------------------+
| Words                                |
+--------------------------------------+
| Value1. Value2 .Value3.Value4.Value5 |
+--------------------------------------+
1 row in set (0.00 sec)

Here is the query to get everything before the last occurrence of a character in MySQL −

mysql> update DemoTable
   -> set Words=REVERSE(SUBSTRING(REVERSE(Words), INSTR(REVERSE(Words),'.')));
Query OK, 1 row affected (0.13 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

Output

This will produce the following output −

+--------------------------------+
| Words                          |
+--------------------------------+
| Value1. Value2 .Value3.Value4. |
+--------------------------------+
1 row in set (0.00 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jun-2020

422 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements