Substr Function In Sql in SQL
The SUBSTR function in SQL is used to extract a substring from a given string starting at a specified position for a specified length.
? Syntax
SUBSTR(string, start_position, length)string: The source string.start_position: The position to start extracting (1-based index).length(optional): Number of characters to extract. If omitted, extracts till the end of the string.
? Return
Returns a substring starting from
start_position.If
lengthis provided, returns that many characters; otherwise, returns to the end.
? Examples
SELECT SUBSTR('OpenAI ChatGPT', 1, 6) AS Substring1; -- Returns 'OpenAI'SELECT SUBSTR('OpenAI ChatGPT', 8) AS Substring2; -- Returns 'ChatGPT'SELECT SUBSTR('OpenAI ChatGPT', 5, 10) AS Substring3; -- Returns 'AI ChatGPT'? Notes
In some SQL dialects, the function is named
SUBSTRING()but usage is similar.start_positionis usually 1-based (first character is position 1).Negative
start_positionvalues may count from the end in some databases (e.g., Oracle).
Dialect Differences
| Database | Function Name | Notes |
|---|---|---|
| Oracle, MySQL | SUBSTR | Commonly used |
| SQL Server | SUBSTRING | Same functionality |
| PostgreSQL | SUBSTRING | Supports standard syntax |
If you want, I can also provide equivalent examples for your specific SQL dialect!