Substring Function In Sql in SQL
The SUBSTRING function in SQL is used to extract a portion of a string, starting at a specified position, optionally for a given length.
? Syntax
SUBSTRING(string, start_position, length)string: The source string.start_position: The starting position (1-based index).length: Number of characters to extract.
? Behavior
Extracts a substring beginning at
start_position.Extracts
lengthcharacters from the starting point.If
lengthexceeds the string’s remaining length, returns up to the end.If
start_positionis beyond the string length, returns an empty string.Some dialects allow
start_positionto be negative to count from the end.
? Examples
SELECT SUBSTRING('OpenAI ChatGPT', 1, 6) AS Extracted; -- 'OpenAI'SELECT SUBSTRING('OpenAI ChatGPT', 8, 7) AS Extracted; -- 'ChatGPT'SELECT SUBSTRING('OpenAI ChatGPT', 8) AS Extracted; -- 'ChatGPT' (if length omitted in some DBs)Dialect Notes
| Database | Function Name | Notes |
|---|---|---|
| SQL Server | SUBSTRING | Requires all three parameters |
| MySQL | SUBSTRING or SUBSTR | length is optional |
| PostgreSQL | SUBSTRING | Supports various syntaxes |
| Oracle | SUBSTR | Similar behavior |
If you want, I can show you how to use SUBSTRING in your specific SQL database!