SUBSTRING is a scalar string-manipulation function defined in the SQL standard and implemented by virtually every major database. It extracts a contiguous sequence of characters from a source string based on a 1-based start position and, optionally, a length. If the length argument is omitted, the function returns the rest of the string from the start position to the end.Two syntactic forms exist:1. Standard form: SUBSTRING(source FROM start [FOR length])2. Functional form used by many vendors: SUBSTRING(source, start, length)Behavioral notes:- Indexing is 1-based in all common dialects.- If start_position is less than 1 the result is implementation-defined (most return an empty string).- If start_position exceeds the source length, the result is an empty string.- If length is negative or zero, most systems raise an error.- Binary data variants (SUBSTRING for BYTEA/BLOB) follow the same rules.Differences by dialect:- Oracle and SQLite expose the same capability under the alias SUBSTR, but also accept SUBSTRING.- SQL Server requires the functional form with all three arguments.- PostgreSQL accepts both forms and supports extraction from bytea and bit strings.Performance is O(n) in the length requested and generally inexpensive because no scanning beyond the requested region is performed.
source_string
(string) - the input text or byte sequencestart_position
(integer) - 1-based index of the first character to extractsubstring_length
(integer, optional) - number of characters to return. If omitted, returns to end of stringLEFT, RIGHT, CHARINDEX, POSITION, LENGTH, TRIM
SQL-92
Use SUBSTRING with LENGTH:```sqlSELECT SUBSTRING(col FROM LENGTH(col) - 3 + 1 FOR 3) FROM t;```
Yes. If you only supply source and start, SUBSTRING returns from the start position to the end of the string in dialects that allow the two-argument form (e.g., MySQL, PostgreSQL).
In PostgreSQL, SQL Server, and others, SUBSTRING operates on binary types as well, following the same rules.
SQL Server's syntax requires all three arguments. Provide the length or switch to LEFT/RIGHT for simpler use cases.