Sub topic 1
Working with Strings in Oracle: Positions and NULLs
Prerequisites
This chapter assumes you can write basic SELECT statements with a WHERE clause, you know what VARCHAR2 columns and string literals are, and you understand that DUAL is a one-row table used for testing expressions. You should also know that NULL means "no value."
Working with strings in Oracle: positions and NULLs
Oracle numbers character positions from 1, so the first character of a string is at position 1. Oracle also treats an empty string as NULL. Test for an empty value with IS NULL, not with = ''. Most functions return NULL when any argument is NULL.
SUBSTR: extracting part of a string
SUBSTR(string, start, length) returns part of a string. The length is optional. Without it, SUBSTR returns everything from the start position to the end.
SELECT SUBSTR('Oracle Database', 1, 6) AS first_word,
SUBSTR('Oracle Database', 8) AS rest
FROM dual;
-- first_word = 'Oracle', rest = 'Database'A start of 0 behaves like 1. A start past the end of the string, or a length below 1, returns NULL.
SELECT SUBSTR('abc', 0, 2) AS pos_zero,
SUBSTR('abc', 5) AS past_end,
SUBSTR('abc', 1, 0) AS zero_len
FROM dual;
-- pos_zero = 'ab', past_end = NULL, zero_len = NULLA negative start counts back from the end of the string. SUBSTR('Oracle Database', -8) returns 'Database'.
INSTR: finding where a substring starts
INSTR(string, search) returns the 1-based position of the first match, or 0 when nothing matches. Compare the result with 0 to detect a missing match.
SELECT INSTR('[email protected]', '@') AS at_pos,
INSTR('[email protected]', '#') AS missing
FROM dual;
-- at_pos = 5, missing = 0Combine INSTR and SUBSTR to split text at a delimiter:
SELECT SUBSTR(email, 1, INSTR(email, '@') - 1) AS username,
SUBSTR(email, INSTR(email, '@') + 1) AS domain
FROM (SELECT '[email protected]' AS email FROM dual);
-- username = 'user', domain = 'example.com'Exercise
What does SUBSTR('Oracle', 0, 3) return?
Show answer
'Ora'. A start of 0 behaves like 1, so the function returns the first three characters.