I am using Oracle 11g. I am using the Scott account and the demo EMP table. I inserted one record with ENAME BRUCE WILLIAM. My aim is to show the first name and last name in two columns. I used this code:
select trim rpad(ename, instr(ename,' '))) "First Name",
trim(substr(ename, instr(ename,' '))) "Last Name"
from emp;
This gives a weird result. The First Name is extended to second line. I used
select trim(substr(ename, 1, instr(ename,' '))),
trim(substr(ename, instr(ename, ' ')))
from emp;
I got the expected output. My question is why the first line of query is giving extra spaces?
You are not getting extra spaces in your string, and if you were then the
trim()would remove them again. SQL*Plus is just formatting the results in a way you don’t expect. The documentation mentions the default formatting for column types, and can usually work it out for system functions (though the characterset can make it bigger than you expect).It seems like SQL*Plus, and SQL Developer, can’t determine a sensible default for your
rpadcase, but can for yoursubstr. Well, SQL*Plus is really just getting a result set cursor from the database, and using the cursor metadata to determine the default widths to apply to the fields for display, so it isn’t getting the length you expect from that metadata. But what length should it use?The database only knows how big the
rpadvalue can be if the padding length is a simple value – it doesn’t even mind zero (it returns null, which you’re relying on). If the padding length is determined by a function then there’s no way to tell how big the result could be, apart from calculating it for every value in the result set before returning the metadata and and actual data, which isn’t practical, and would produce inconsistent output as the data changed.It also wouldn’t be practical to try to determine a theoretical maximum, even though it looks superficially straightforward in your case.
substrcan’t ever return something longer than the original value; butrpadcould potentially produce something huge even from a short input value, so it has to allow for that possibility if it can’t easily determine a limit (i.e. from a fixed value).So it plays safe and allows for it being up to the maximum length for a
varchar2, which is 4000 characters, as this dynamic SQL demonstrates:As you can see, it knows the length for a fixed-length
rpadand asubstr(note the size is four times the actual string length due to the multibyte characterset), but falls back to the maximum for therpadusing a function.What you’re seeing is SQL*Plus showing a 4000-char column. If you did this in SQL Developer you would see the header for that column is indeed 4000 characters. SQL*Plus helps a bit by reducing the displayed column header to the line size, and wraps the next column onto a separate line.