Tutorialspoint

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


1 Answer
Sharon Christine

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;

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;

This will produce the following output −

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.