Tutorialspoint

1 Answer
George John

To remove last char if it is a specific character then use SUBSTRING(). Let us first create a table −

mysql> create table DemoTable
   (
   SubjectName varchar(100)
   );
Query OK, 0 rows affected (0.47 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('MySQL');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('MongoDB?');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Java?');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('C');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-------------+
| SubjectName |
+-------------+
| MySQL       |
| MongoDB?    |
| Java?       |
| C           |
+-------------+
4 rows in set (0.00 sec)

Here is the query to remove last char if it's a specific character, for example question mark (?) here −

mysql> update DemoTable SET SubjectName = SUBSTRING(SubjectName, 1, CHAR_LENGTH(SubjectName) - 1)
   where SubjectName like '%?';
Query OK, 2 rows affected (0.25 sec)
Rows matched : 2 Changed : 2 Warnings : 0

Let us check the table records once again −

mysql> select *from DemoTable;

Output

+-------------+
| SubjectName |
+-------------+
| MySQL       |
| MongoDB     |
| Java        |
| C           |
+-------------+
4 rows 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.