In this tutorial, we will learn about CHARINDEX() function in SQL. For learning this further, we have to be familiar with SQL.
SQL stands for Structured Query Language. It is used to create and access data from the database. For accessing the data from the database in SQL, we have to write a query. The query is basically a SELECT statement that is used to access the data from the database.
More About SQL
SQL function CHARINDEX() is used to find the index value of the specified character or substring in the specified string. And if the character is not found then it will return 0.
SQL CHARINDEX() function Syntax
CHARINDEX(substring/character, string , begin)
substring/character: Here substring/character is that value whose position you wanna know.
string: String is, in which you want to know the position of your specified substring/character.
begin: It is a value from which you want to start to search your specified substring/character. This is optional. By default, its value is one.
SQL CHARINDEX Function Examples
Let’s understand with the help of some examples :
SELECT CHARINDEX('c','country') As position
SELECT CHARINDEX('t','country') As position
SELECT CHARINDEX('h','country') As position
SELECT CHARINDEX(' are ','We are Indians') As position
Note: Here we take space at both sides of ‘are’. That means it will search space first.
SELECT CHARINDEX('are','We are Indians') As position
Note: Here we take “are” without spaces.
SELECT CHARINDEX('c','country',3) As position
Note: It will start searching for the position of character ‘c’ from the 3 positions.
SELECT CHARINDEX('c','councctry',3) As position
Note: it will only give the position of the first occurrence of the specified character.