The SQL SUBSTRING function is used to extract a portion of a string value from a larger string. The syntax for the function is as follows:
SUBSTRING(string, start, length)
Where string is the input string value, start is the starting position from which the substring is to be extracted, and length is the number of characters to be extracted. The start parameter is 1-based, meaning that the first character in the string has a position of 1.
Here’s an example of using the SUBSTRING function to extract a substring from a string:
SELECT SUBSTRING('Hello, world!', 7, 6)
This would return the substring ‘world’ from the input string ‘Hello, world!’, starting at position 7 and extracting 6 characters.
The SUBSTRING function is often used in conjunction with other SQL functions, such as the CONCAT function, to manipulate string values in SQL queries. For example, the following query concatenates the first three characters of the ‘first_name’ column and the first four characters of the ‘last_name’ column in a table called ’employees’:
SELECT CONCAT(SUBSTRING(first_name, 1, 3), SUBSTRING(last_name, 1, 4)) AS initials FROM employees;
This would return a column called ‘initials’ containing the concatenated substrings for each row in the ’employees’ table.
Overall, the SQL SUBSTRING function is a useful tool for extracting substrings from string values in SQL queries, allowing for more advanced manipulation and analysis of data.