8

you would think this is answered somewhere but I cant find the exact answer. I need to remove the very last character in a string, it can be any character and the string can be any length.

example 992899d needs to be 992899

1
  • No, it is not. The answer there would just display the stripped value and not actually delete the last character and store it back to the database. May 20, 2016 at 5:45

3 Answers 3

21

Any solution using SUBSTRING would only display the field's content by deleting the last character. It would not actually update the content of the column. If that is what you want(i.e. using it with SELECT) then SUBSTRING is enough.

But, if you want to actually update the value of the column, you can try the following:

UPDATE <table_name>
SET <column_name> = CONCAT(LEFT(<column_name>, CHAR_LENGTH(<column_name>) -1), '')
WHERE <condition>;

This would replace the last character with nothing, hence the last character would be deleted.

Refer: http://dev.mysql.com/doc/refman/5.7/en/string-functions.html

1
  • Concatenating the empty string is unnecessary; the following query would do the same thing: UPDATE <table_name> SET <column_name> = LEFT(<column_name>, CHAR_LENGTH(<column_name>) -1) WHERE <condition>; Nov 10, 2021 at 23:36
10

You are probably looking for SUBSTRING(column, 1, CHAR_LENGTH(column)-1).

See http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring for reference.

1
  • for anybody that runs unit testing through SQLite, the expression compatible with both MySQL and SQLite is SUBSTR(column, 1, LENGTH(column)-1)
    – dave
    Oct 5, 2022 at 9:12
2

Use TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM ] str) because you already know what section of the string you want to be removed.

Here is a table with dates and a given quantity that I pulled from my database:

select date_format(date, '%m/%d %I:%i%p') as Date ...
Date        | QTY
-------------------
3/5 11:30AM | 46
3/5 11:30PM | 23
3/6 11:30AM | 12
...

Using Trim:

select trim(trailing 'M' from date_format(date, '%m/%d %I:%i%p')) as Date ...
Date        | QTY
-------------------
3/5 11:30A  | 46
3/5 11:30P  | 23
3/6 11:30P  | 12
...

Credit to https://www.w3resource.com/mysql/string-functions/mysql-trim-function.php for helping me understand trim

Not the answer you're looking for? Browse other questions tagged or ask your own question.