How is the substring function used in SQL?
The SUBSTRING function in SQL is used to extract a substring from a string.
Syntax:
SUBSTRING(string, start, length)
Explanation of Parameters:
- string: the string from which to extract a substring.
- Starting position of the substring. The index of the starting position starts counting from 1.
- Length: The length of the substring to be extracted. If this parameter is omitted, all characters from the starting position to the end of the string will be extracted.
Given a string “Hello, World!”, you can extract a substring from it using the SUBSTRING function.
- Extract a substring starting from the 6th character:
SELECT SUBSTRING(‘Hello, World!’, 6);
Result: ” World!” - Extract a substring starting from the first character for a length of 5 characters:
SELECT SUBSTRING(‘Hello, World!’, 1, 5);
Result will be “Hello” - Extract a substring of the first three characters starting from the 8th character:
SELECT SUBSTRING(‘Hello, World!’, 8, 3);
The result is “Wor”.