Sub topic 12
Byte and Character Semantics: SUBSTRB, SUBSTRC, INSTRB
This chapter assumes you know SUBSTR, INSTR, and REPLACE with positive and negative positions, and that you know the edge cases from earlier chapters. It also assumes you have a basic idea of what a character set is. Every position you have used so far was a count of characters. This chapter covers the variants that count something else.
Why a "position" needs a unit
A position such as 4 means "the fourth something". In a single-byte character set such as WE8ISO8859P1, every character is one byte, so the something is always the same. In a multibyte character set such as AL32UTF8 (the usual choice for modern Oracle databases), a character can take one to four bytes. Then "the fourth character" and "the fourth byte" can be different places.
Oracle exposes the choice through a family of functions that share one suffix convention.
| Suffix | Counts in | Example functions |
|---|---|---|
| none | Characters, as defined by the character set of the input | `SUBSTR`, `INSTR`, `LENGTH` |
| `B` | Bytes | `SUBSTRB`, `INSTRB`, `LENGTHB` |
| `C` | Unicode complete characters (a base character plus its combining marks) | `SUBSTRC`, `INSTRC`, `LENGTHC` |
| `2` | UCS2 code units (UTF-16 units) | `SUBSTR2`, `INSTR2`, `LENGTH2` |
| `4` | UCS4 code points | `SUBSTR4`, `INSTR4`, `LENGTH4` |
This chapter focuses on the B and C forms, which you will meet most often. The 2 and 4 forms follow the same pattern and matter mainly when you work with surrogate pairs in UTF-16 data.
Check your own database character set before running the examples:
SELECT parameter, value
FROM nls_database_parameters
WHERE parameter IN ('NLS_CHARACTERSET', 'NLS_NCHAR_CHARACTERSET', 'NLS_LENGTH_SEMANTICS');The examples below assume NLS_CHARACTERSET = AL32UTF8. They build their strings with UNISTR, which takes Unicode escapes, so the results do not depend on your client's encoding.
Characters versus bytes with LENGTH and LENGTHB
Start by measuring. LENGTHB is the quickest way to see whether a string contains multibyte characters.
SELECT LENGTH(s) AS chars,
LENGTHB(s) AS bytes
FROM (SELECT UNISTR('Caf\00E9') AS s FROM dual);
-- chars = 4, bytes = 5 in AL32UTF8The letter é (U+00E9) takes two bytes in UTF-8, so the string has 4 characters and 5 bytes. A useful audit query finds rows where the two counts differ:
SELECT id, name
FROM customers
WHERE LENGTHB(name) > LENGTH(name);This query returns every row whose name contains at least one multibyte character. The customers table is a placeholder for your own table.
SUBSTRB: extracting by byte position
SUBSTRB(string, position [, length]) has the same shape as SUBSTR, but position and length are byte counts. Negative positions, position 0, and the NULL rules behave as they do for SUBSTR, with bytes as the unit.
On a string made only of single-byte characters, the two functions agree:
SELECT SUBSTR('Oracle', 2, 3) AS by_chars,
SUBSTRB('Oracle', 2, 3) AS by_bytes
FROM dual;
-- both 'rac'On multibyte text they diverge. Each of the three Japanese characters in 日本語 takes 3 bytes in AL32UTF8:
SELECT SUBSTR(s, 1, 2) AS two_chars,
SUBSTRB(s, 1, 6) AS six_bytes,
SUBSTRB(s, 1, 4) AS four_bytes
FROM (SELECT UNISTR('\65E5\672C\8A9E') AS s FROM dual);
-- two_chars = '日本'
-- six_bytes = '日本'
-- four_bytes = '日' followed by a spaceThe third result is the main risk of SUBSTRB. Four bytes cut the second character after its first byte. In a multibyte database character set, Oracle does not return the broken byte. It replaces the partial character with a space. The result is valid text, but it has a character you did not ask for. Confirm this behavior in your own database before you rely on it.
Where SUBSTRB is the right tool
Use SUBSTRB when the limit you must respect is in bytes:
- A
VARCHAR2(n BYTE)column, or any column whereNLS_LENGTH_SEMANTICSisBYTE, limits storage in bytes. - The 4000-byte limit on
VARCHAR2in SQL (whenMAX_STRING_SIZE = STANDARD) is counted in bytes. - A file format or network protocol with fixed byte-width fields also counts in bytes.
Truncating with SUBSTR(text, 1, 10) does not guarantee 10 bytes or fewer. Ten characters of Japanese text need 30 bytes. SUBSTRB(text, 1, 10) guarantees the byte limit but may leave a trailing space where a character was cut.
SELECT SUBSTRB(s, 1, 10) AS truncated,
LENGTHB(SUBSTRB(s, 1, 10)) AS bytes_used
FROM (SELECT UNISTR('\65E5\672C\8A9E\65E5\672C\8A9E') AS s FROM dual);
-- truncated = '日本語' followed by one space; bytes_used = 10Three whole characters take 9 bytes. The tenth byte is the first byte of the fourth character, so Oracle returns a space in its place.
A column declared with character semantics, such as VARCHAR2(10 CHAR), behaves differently from byte semantics when you insert. It accepts 10 characters whatever their byte size, up to the 4000-byte ceiling. Check how the target column is declared before you choose between SUBSTR and SUBSTRB.
INSTRB: finding a position in bytes
INSTRB(string, substring [, position [, occurrence]]) returns the byte position of the match. The position argument is also in bytes.
SELECT INSTR(s, UNISTR('\8A9E')) AS char_pos,
INSTRB(s, UNISTR('\8A9E')) AS byte_pos
FROM (SELECT UNISTR('\65E5\672C\8A9E') AS s FROM dual);
-- char_pos = 3, byte_pos = 7The match 語 is the third character, and it starts at byte 7, after six bytes of 日本.
A byte position is only safe to feed to a function that uses bytes. Do not mix the two families:
-- Wrong: a byte position given to a character-based function
SELECT SUBSTR(s, INSTRB(s, UNISTR('\8A9E')))
FROM (SELECT UNISTR('\65E5\672C\8A9E') AS s FROM dual);
-- INSTRB returns 7, SUBSTR starts at character 7, past the end: NULLThe consistent pairs are SUBSTR with INSTR, and SUBSTRB with INSTRB. The parsing patterns from the earlier chapters work unchanged if you swap in the matching pair:
SELECT SUBSTRB(s, 1, INSTRB(s, ',') - 1) AS before_comma,
SUBSTRB(s, INSTRB(s, ',') + 1) AS after_comma
FROM (SELECT UNISTR('\65E5\672C,\8A9E') AS s FROM dual);
-- before_comma = '日本', after_comma = '語'Here the comma is a single-byte character, so adding 1 to its byte position lands on the first byte of the next character. If the delimiter were itself multibyte, you would add its LENGTHB instead of 1.
SUBSTRC and INSTRC: complete Unicode characters
Unicode can write one visible character as several code points. The letter é can be one code point (U+00E9), or a plain e followed by a combining acute accent (U+0301). The first form is precomposed and the second is decomposed. They look the same on screen.
SUBSTR counts each code point as a character. That means it can separate a base letter from its accent. SUBSTRC counts a base character together with its combining marks as one unit.
SELECT LENGTH(s) AS code_points,
LENGTHC(s) AS complete_chars,
LENGTHB(s) AS bytes,
SUBSTR(s, 1, 1) AS by_code_point,
SUBSTRC(s, 1, 1) AS by_complete_char
FROM (SELECT UNISTR('e\0301') AS s FROM dual);
-- code_points = 2, complete_chars = 1, bytes = 3
-- by_code_point = 'e' (the accent is dropped)
-- by_complete_char = 'é' (letter and accent together)INSTRC gives positions in the same unit:
SELECT INSTR(s, 'x') AS code_point_pos,
INSTRC(s, 'x') AS complete_char_pos
FROM (SELECT UNISTR('e\0301x') AS s FROM dual);
-- code_point_pos = 3, complete_char_pos = 2Use the C variants when you cut text for display, such as a preview of the first 20 characters. Cutting between a letter and its accent leaves a stray e or a floating accent mark. For plain ASCII data they give the same answers as SUBSTR and INSTR.
Choosing the right variant
Pitfalls
- Mixing units. Passing the result of
INSTRBtoSUBSTR, or the reverse, gives wrong or NULL results on multibyte data. It works by accident on ASCII test data, so the bug appears only in production. - Testing only with ASCII. Include at least one multibyte string, such as
UNISTR('\00E9')or Japanese text, in your tests. - Trusting a trailing space. After
SUBSTRB, a space may be the replacement for a cut character. ApplyingRTRIMremoves real trailing spaces too, so compareLENGTHBbefore and after if the difference matters. - Forgetting national character types.
NVARCHAR2andNCHARuse the national character set (NLS_NCHAR_CHARACTERSET). Byte counts there follow that set, which is oftenAL16UTF16with 2 bytes for most characters, not your database set. - Replacement with REPLACE.
REPLACEhas no byte variant. It matches whole characters, so it never splits a multibyte character.
Exercise
The database character set is AL32UTF8 and s is UNISTR('Caf\00E9'), the text "Café" with a precomposed é. Give the value of each: LENGTH(s), LENGTHB(s), SUBSTR(s, 4, 1), and SUBSTRB(s, 4, 2). Then say what SUBSTRB(s, 5, 1) returns and why.
Show answer
LENGTH(s) = 4 characters and LENGTHB(s) = 5 bytes, because é takes two bytes. SUBSTR(s, 4, 1) = 'é', the fourth character. SUBSTRB(s, 4, 2) = 'é', because the character occupies bytes 4 and 5. SUBSTRB(s, 5, 1) starts on the second byte of é, so it returns only part of a multibyte character. Oracle replaces that partial character with a space instead of returning a broken byte.
Exercise
A column holds the string UNISTR('e\0301x'), a letter e, a combining acute accent, and the letter x. You want the first visible character, including its accent. Which of SUBSTR(s, 1, 1) and SUBSTRC(s, 1, 1) do you use, and what does INSTRC(s, 'x') return?
Show answer
Use SUBSTRC(s, 1, 1). It returns the letter and its accent together, while SUBSTR(s, 1, 1) returns only the plain 'e'. INSTRC(s, 'x') returns 2, because the e and its accent count as one complete character and x is the second. INSTR(s, 'x') would return 3, counting code points.