Strip last two characters of a column in MySQL

MysqlSqlString

Mysql Problem Overview


I have an SQL column where the entries are strings. I need to display those entries after trimming the last two characters, e.g. if the entry is 199902345 it should output 1999023.

I tried looking into TRIM but looks like it offers to trim only if we know what are the last two characters. But in my case, I don't know what those last two numbers are and they just need to be discarded.

So, in short, what MySQL string operation enables to trim the last two characters of a string?

I must add that the length of the string is not fixed. It could be 9 characters, 11 characters or whatsoever.

Mysql Solutions


Solution 1 - Mysql

To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING and CHAR_LENGTH functions together:

SELECT col
     , /* ANSI Syntax  */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
     , /* MySQL Syntax */ SUBSTRING(col,     1,    CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl

To remove a specific substring from the end of string, use the TRIM function:

SELECT col
     , TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.php.php becomes index (!)
-- index.txt remains index.txt

Solution 2 - Mysql

Why not using LEFT(string, length) function instead of substring.

LEFT(col,char_length(col)-2) 

you can visit here https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_left to know more about Mysql String Functions.

Solution 3 - Mysql

Solution 4 - Mysql

You can use a LENGTH(that_string) minus the number of characters you want to remove in the SUBSTRING() select perhaps or use the TRIM() function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLucky MurariView Question on Stackoverflow
Solution 1 - MysqlSalman AView Answer on Stackoverflow
Solution 2 - MysqlLarzView Answer on Stackoverflow
Solution 3 - MysqlDenis de BernardyView Answer on Stackoverflow
Solution 4 - MysqlRichardView Answer on Stackoverflow