I am trying to fetch an id from an oracle table. It\'s something like TN0001234567890345
. What I want is to sort the values according to the right most 10 posit
Another way of doing it though more tedious. Use the REVERSE
and SUBSTR
functions as indicated below:
SELECT REVERSE(SUBSTR(REVERSE('TN0001234567890345'), 1, 10)) FROM DUAL;
The first REVERSE function will return the string 5430987654321000NT
.
The SUBSTR
function will read our new string 5430987654321000NT
from the first character to the tenth character which will return 5430987654.
The last REVERSE
function will return our original string minus the first 8 characters i.e. 4567890345
codaddict's solution works if your string is known to be at least as long as the length it is to be trimmed to. However, if you could have shorter strings (e.g. trimming to last 10 characters and one of the strings to trim is 'abc') this returns null which is likely not what you want.
Thus, here's the slightly modified version that will take rightmost 10 characters regardless of length as long as they are present:
select substr(colName, -least(length(colName), 10)) from tableName;
Yeah this is an old post, but it popped up in the list due to someone editing it for some reason and I was appalled that a regular expression solution was not included! So here's a solution using regex_substr in the order by clause just for an exercise in futility. The regex looks at the last 10 characters in the string:
with tbl(str) as (
select 'TN0001239567890345' from dual union
select 'TN0001234567890345' from dual
)
select str
from tbl
order by to_number(regexp_substr(str, '.{10}$'));
An assumption is made that the ID part of the string is at least 10 digits.
You can use SUBSTR function as:
select substr('TN0001234567890345',-10) from dual;
Output:
4567890345