Truncating a string to N bytes using SUBSTRB
A VARCHAR2 variable or database column is declared with a certain maximum size, expressed as a number of characters or bytes; a VARCHAR2(100 CHAR) allows any string up to 100 characters, whereas a VARCHAR2(100 BYTE) allows any string that can fit within 100 bytes.
Both of these will accept single- and multi-byte characters; however they differ in how long a string they will accept.
We can create a simple test case – construct a string with 3,999 single-byte characters, followed by a multi-byte character. We can examine the length of the string using LENGTH (to get the number of characters) and LENGTHB (to get the size in bytes):
declare
l_string varchar2(4000 char);
begin
l_string := lpad('a',3999,'a') || '€';
dbms_output.put_line('characters: ' || LENGTH(l_string));
dbms_output.put_line('bytes: ' || LENGTHB(l_string));
end;
/
characters: 4000
bytes: 4002
From this test case we can see that our final character (“€”) requires 3 bytes to store it.
Note: these tests were run on a database using the AL32UTF8 character set. Results may differ on databases with other character sets; in particular, supplementary characters may be treated as separate characters for the purpose of truncation.
A common scenario is a table column declared as VARCHAR2(4000); unless extended strings are enabled, the database will limit this to 4000 bytes. A PL/SQL string declared as VARCHAR2(4000 char) will allow up to 4000 characters; if there are some multi-byte characters in there, it will fail with ORA-12899: value too large for column if we try to insert that into the table:
create table t (a varchar2(4000 byte));
declare
l_string varchar2(4000 char);
begin
l_string := lpad('a',3999,'a') || '€';
insert into t (a) values (l_string);
end;
/
ORA-12899: value too large for column "DEMO"."T"."A" (actual: 4002, maximum: 4000)
Let’s say you don’t care if some multi-byte characters at the end of a long string are lost, you just want to store as much as possible within the 4000-byte limit but you don’t want to corrupt or split up any multi-byte characters. The obvious choice might be to use SUBSTR to truncate the string:
declare
l_string varchar2(4000 char);
begin
l_string := lpad('a',3999,'a') || '€';
insert into t (a) values ( SUBSTR(l_string, 1, 4000) );
end;
/
ORA-12899: value too large for column "DEMO"."T"."A" (actual: 4002, maximum: 4000)
That didn’t work, because SUBSTR uses character-length semantics; it effectively returned the same string of exactly 4000 characters. If we reduce the size, e.g. trim it to an arbitrarily smaller length of 2000 or 1000 characters, it should fit in most cases. However, we’re now losing a lot more data, and there may be some strings with many multi-byte characters (e.g. a message using many Japanese or Chinese characters, or supplementary characters) that might still not fit and fail to be inserted even after selecting a much smaller number of characters.
We need to use its byte-length variant, SUBSTRB. This returns a substring starting from a given character offset (the 1st character, in this example), and only returns a string that will fit within the given maximum number of bytes (4000, in this example):
declare
l_string varchar2(4000 char);
begin
l_string := lpad('a',3999,'a') || '€';
insert into t (a) values ( SUBSTRB(l_string, 1, 4000) );
end;
/
PL/SQL procedure successfully completed.
Let’s look at the result:
select length(a), lengthb(a) from t;
LENGTH(A) LENGTHB(A)
---------- ----------
4000 4000
We know that that final character requires 3 bytes to store, so what has SUBSTRB done with it? Let’s examine what’s actually been stored at that location. We’ll take a substring starting from the last 'a' just before the last character in the string, and use the DUMP function to find out exactly what has been stored there.
select
'[...' || substr(a, 3999) || ']' a,
DUMP(substr(a, 3999)) b
from t;
A B
------- ------------------
[...a ] Typ=1 Len=2: 97,32
As expected, there is a character 'a' (ascii 97) at offset 3999. However, at offset 4000 we see a simple space character (ascii 32). We weren’t expecting our Euro character, because it cannot be squashed into a single byte, but we weren’t expecting SUBSTRB to replace it with anything.
From this we can divine that whenever SUBSTRB can’t fit a multi-byte character into the requested maximum number of bytes, it will drop the trailing character(s) and pad the result with spaces. This specific behaviour is not documented – in fact, the documentation for SUBSTRB leaves this behaviour undefined. In most cases, however, this is not a big issue.
Alternative Approaches
I’ve been informed that the preferred behaviour would be that multi-byte characters that cannot fit should be simply omitted from the result and not replaced with any padding. This would then return a string that may be shorter than the requested number of bytes.
Oracle has not implemented this preferred behaviour of SUBSTRB (in the default case) mainly due to a need to maintain backwards compatibility with existing code that currently expects the padding.
If you don’t want the spaces, there are a few approaches with varying results:
Option 1. Use RTRIM to drop the trailing space(s)
declare
l_string varchar2(4000 char);
begin
l_string := lpad('a',3999,'a') || '€';
insert into t (a) values ( RTRIM(substrb(l_string, 1, 4000)) );
end;
/
PL/SQL procedure successfully completed.
select
'[...' || substr(a, 3999) || ']' a,
dump(substr(a, 3999)) b
from t;
A B
------- ---------------
[...a] Typ=1 Len=1: 97
This works fine, but it’s a bit heavy-handed. What if the original string was composed of some ordinary spaces at the end and you wanted those to be retained? They will be silently removed by the call to RTRIM. If that’s not a concern, however, this method works fine.
Option 2. Use the NO_SUBSTRB_PAD hint (SQL only)
If you’re querying a table that has long strings, potentially containing multi-byte characters, and you want to limit the size of the result, and you don’t want to use the RTRIM method, this is a potential solution. I’ve been informed the NO_SUBSTRB_PAD hint invokes the preferred behaviour of SUBSTRB which is to drop multi-byte characters that cannot fit.
with src as (
select 'aaa€' as a
from dual
)
select /*+ NO_SUBSTRB_PAD */
'[' || substrb(a, 1, 4) || ']' a,
dump(substrb(a, 1, 4)) b
from src;
A B
----- ---------------------
[aaa] Typ=1 Len=3: 97,97,97
This hint is not documented but has been mentioned elsewhere. It affects all references to the SUBSTRB function within the query.
Option 3. Use a custom function
The following function removes trailing characters from the end of the string so that the result is guaranteed to fit within the given number of bytes:
create function truncate_bytes (
p_text in varchar2,
p_max_bytes in pls_integer
) return varchar2 deterministic
is
--
-- TRUNCATE_BYTES returns a string guaranteed to fit
-- within p_max_bytes bytes, containing the maximum
-- number of full characters (whether multibyte or
-- otherwise) from the start of p_text. The result
-- may have fewer than p_max_bytes bytes.
--
l_low pls_integer := 0;
l_high pls_integer;
l_mid pls_integer;
begin
if p_max_bytes is null or p_max_bytes < 0 then
raise value_error;
elsif p_text is null or p_max_bytes = 0 then
return null;
elsif lengthb(p_text) <= p_max_bytes then
return p_text;
end if;
l_high := least(lengthc(p_text), p_max_bytes);
while l_low < l_high loop
l_mid := l_low + trunc((l_high - l_low + 1) / 2);
if lengthb(substrc(p_text, 1, l_mid)) <= p_max_bytes then
l_low := l_mid;
else
l_high := l_mid - 1;
end if;
end loop;
return substrc(p_text, 1, l_low);
end;
declare
l_string varchar2(4000 char);
begin
l_string := lpad('a',3999,'a') || '€';
l_string := TRUNCATE_BYTES(l_string, 4000);
insert into t (a) values ( l_string );
end;
/
PL/SQL procedure successfully completed.
select
'[...' || substr(a, 3999) || ']' a,
dump(substr(a, 3999)) b
from t;
A B
------- ---------------
[...a] Typ=1 Len=1: 97
The downsides to this approach are that it requires compiling a function in your schema, and it will not perform as well as native database functions. Benchmark it before calling it from a SQL query across a large data set.
Note that the function uses LENGTHC and SUBSTRC when determining how many characters to lop off the end of the string. These variants treat each supplementary Unicode character as one complete character, even when the database character set would otherwise count its surrogate pair as two units. Supplementary characters include many emoji, some mathematical and musical symbols, additional Chinese/Japanese/Korean ideographs, and characters from writing systems such as Egyptian hieroglyphs.
Option 4. Modify the database session (undocumented)
Setting event 10943 at level 524288 will invoke the alternative behaviour of all calls to SUBSTRB, whether in SQL or PL/SQL. However, as this is undocumented, make sure you raise an SR and get written approval from Oracle Support before using it.
alter session set events '10943 trace name context forever, level 524288';
declare
l_string varchar2(4000 char);
begin
l_string := lpad('a',3999,'a') || '€';
dbms_output.put_line('[' || substrb(l_string, 3999, 2) || ']');
end;
/
[a]
Huge thanks to Connor McDonald for valuable discussions and for digging up some details I’ve shamelessly reproduced in this post. If there are any errors in this article, however, they are almost certainly mine!
Related:
