How do you use the SUBSTRING function to extract a substring from a string?
Posted by FrankMl
Last Updated: July 12, 2024
The SUBSTRING function is used in SQL to extract a portion of a string based on specified starting position and length. Here's the general syntax for the SUBSTRING function:
SUBSTRING(string, start_position, length)
- string: The original string from which you want to extract a substring. - start_position: The starting position of the substring (1-based index). - length: The number of characters to extract from the string.
Example Usage
Assume you have a table named Employees with a column named FullName, and you want to extract the first name from the full name, which is the substring before the first space:
SELECT SUBSTRING(FullName, 1, CHARINDEX(' ', FullName) - 1) AS FirstName
FROM Employees;
In this example: - FullName is the string from which we want to extract. - 1 is the starting position (the first character of the string). - CHARINDEX(' ', FullName) - 1 calculates the length by determining the position of the first space and subtracting one to get the length of the first name.
Another Example
If you just want to extract a portion of a string starting at a specific position, you can do so directly:
SELECT SUBSTRING('Hello, World!', 8, 5) AS ExtractedSubstring;
This will return World: - Starting at position 8, it extracts 5 characters.
Notes
- Remember that in most SQL database systems, string indexing starts at 1, not 0. - If the length exceeds the remaining characters from the start_position, it will return up to the end of the string without generating an error. - Be cautious with positions that may not exist (e.g., starting at a position greater than the string length will usually return an empty string).
Related Content