CHARINDEX () is the one of the most commonly used functions of SQL Server. It is used to find out the position of any specific substring in a given string. It takes three parameters; first is the substring whose position is to be find, second is the string in which the substring’s position has to be find and third parameter is the starting location to find out the substring. Third parameter is the optional one. When it is given, the search of the substring will be then started from the index greater than the start location.
Syntax:
CHARINDEX (substring, superstring, start_location)
It can be used only with the SELECT command. The syntax for using it with SELECT command
SELECT
CHARINDEX (substring, superstring, start_location)
AS
String Position
Example:
SELECT
CHARINDEX (‘is’, ‘It is an example’)
AS
String Position
Output:
String Position
4
Another example to show, if start location parameter is given them what would be result.
Example:
SELECT
CHARINDEX (‘the’, ‘the example to obtain the result’, 10)
AS
String Position
Output:
String Position
23
Here, the position of the keyword is given which is greater than the start location.
And, if in case, the given substring is not found in the given string, it will give 0 as a result.