Using substr to trim string on Oracle

Michal Krasny picture Michal Krasny · Jun 17, 2014 · Viewed 49.1k times · Source

I want to trim a string to a specified length. If the string is shorter, I don't want to do anything. I found a function substr() which does the job. However there is nothing in the Oracle documentation what happens if the string is shorter, than maximal length.

For example this:

select substr('abc',1,5) from dual;

returns 'abc', which is what I need.

I'd like to ask if this is safe, because the function seems not to be defined for this usage. Is there a better way how to truncate?

Answer

neshkeev picture neshkeev · Jun 17, 2014

It is totally ok, but if you want, you can use this query:

select substr('abc',1,least(5,length('abc'))) from dual;