Getting last 5 char of string with mysql query

I have to get last 5 numbers using mysql.

My values are like YOT-A78514,LOP-C4521 ...

I have to get only last five char . How can I do this in query?


You can do this with RIGHT(str,len) function. Returns the rightmost len characters from the string str,

Like below:

SELECT RIGHT(columnname,5) as yourvalue FROM tablename

"Right"-function is the way to, using the substring may lead to an problem that is not so easy to notice:

mysql> select right('hello', 6);
+-------------------+
| right('hello', 6) |
+-------------------+
| hello             |
+-------------------+
1 row in set (0.00 sec)

mysql> select substring('hello', -6);
+------------------------+
| substring('hello', -6) |
+------------------------+
|                        |
+------------------------+
1 row in set (0.00 sec)

But if you don't try to go past the start of the string, then substring of course works fine:

mysql> select substring('hello', -5);
+------------------------+
| substring('hello', -5) |
+------------------------+
| hello                  |
+------------------------+
1 row in set (0.00 sec)

Right is a good choice but you can also use substring like this-

SELECT Substring(columnname,-5) as value FROM table_name

SELECT row_id
  FROM column_name
WHERE column_value LIKE '%12345';

This will return the "row_id" when "12345" is found to be the tailing suffix of the "column_value" within the "column_name".