Extract a contiguous slice of characters from the input string (alias of SUBSTRING).
SUBSTR(str, pos, len)
## Overview Returns a contiguous slice of the input string starting at the 1-based character position `pos` and continuing for `len` characters. SUBSTR is an alias of SUBSTRING and behaves identically; choose whichever name matches your project's conventions. Both function names are common in SQL code bases. SUBSTR is often preferred for brevity, especially in scripts that already use SUBSTRING_INDEX or SPLIT_PART for other slicing work. ## Behavior - Returns NULL when any argument is NULL. - Positions are 1-based. - If `pos` is greater than the character length of the string, the result is an empty string. - If `pos + len` extends past the end, the function returns the slice up to the end without error. - If `len` is 0 or negative, the result is an empty string. - Operates on Unicode code points; multi-byte UTF-8 characters count as one position. ## Compatibility - Functionally identical to SUBSTRING in both positional and SQL-standard (FROM/FOR) call forms. - Widely supported across SQL dialects as the short-form slicing function.
| Name | Type | Description |
|---|---|---|
str | Specifies the input string from which the slice is extracted. | |
pos | Specifies the 1-based starting character position. A value of 1 refers to the first character. | |
len | Specifies the number of characters to extract. Non-positive values yield an empty string. A length longer than the remainder returns the remainder without error. |
-- Extract from position 2, length 3
SELECT SUBSTR('hello world', 2, 3); -- 'ell'
-- Extract the final word
SELECT SUBSTR('hello world', 7, 5); -- 'world'
-- Position beyond end returns empty string
SELECT SUBSTR('hello', 10, 3); -- ''
-- Extract first 4 characters
SELECT SUBSTR('abcdef', 1, 4); -- 'abcd'
-- Extract year from an ISO date string column
SELECT SUBSTR(raw_date, 1, 4) AS year_str
FROM ops.etl.staging_invoices;
-- NULL propagates
SELECT SUBSTR(CAST(NULL AS VARCHAR), 1, 3); -- NULL