Take off last character if a specific one exists in a string?


You can use trim() for this.Let us first create a table −

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

Insert some records in the table using insert command. Here, we have added a question mark (?) to the end of some of the strings −

mysql> insert into DemoTable values('User123?');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('User777');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('User456');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('User133?');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------+
| UserId   |
+----------+
| User123? |
| User777  |
| User456  |
| User133? |
+----------+
4 rows in set (0.00 sec)

Following is the query to take off last character if a certain one exists in a string i.e.? in this case −

mysql> select trim(trailing '?' from UserId) from DemoTable;

This will produce the following output −

+--------------------------------+
| trim(trailing '?' from UserId) |
+--------------------------------+
| User123                        |
| User777                        |
| User456                        |
| User133                        |
+--------------------------------+
4 rows in set (0.04 sec)

Updated on: 30-Jul-2019

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements