Open In App

SQL Server CHARINDEX() function

Last Updated : 15 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

CHARINDEX() function in SQL Server returns the position of a substring within a given string. The search performed in this function is case-insensitive.

Syntax

CHARINDEX function syntax is:

CHARINDEX(substring, string, [starting_position]

Parameters

CHARINDEX function accepts 3 parameters:

  1. substring: The substring that we are searching for. It has a limit of 8,000 characters.
  2. string: The string in which searching takes place.
  3. starting_position: The position from which searching will take place. It’s an optional parameter.

Returns

  • The function will return the position of a substring within a given string.
  • If the substring is not found in the string, then the function will return 0.

Applicable to the following versions:

  • SQL Server 2017
  • SQL Server 2016
  • SQL Server 2014
  • SQL Server 2012
  • SQL Server 2008 R2
  • SQL Server 2008
  • SQL Server 2005

SQL Server CHARINDEX() Function Example

Let’s look at some examples of the CHARINDEX() function in SQL Server.

Example 1:

In this example, we are searching a character using the CHARINDEX() function.

SELECT CHARINDEX('k', 'GeeksforGeeks') 
AS Found ;

Output :

Found
4

Example 2:

In this example, we will use of “starting_position” parameter in CHARINDEX() function.

SELECT CHARINDEX
('for', 'Love for all, Hate for none', 10)
AS Found ;

Output :

Found
20

Example 3:

In this example, we will prove that CHARINDEX() function is case-insensitive.

SELECT  
CHARINDEX('Bear', 'Bob likes Bear, beer likes bob')
As Found1,
CHARINDEX('bear', 'Bob likes Bear, beer likes bob')
As Found2 ;

Output :

Found1 Found2
11 11

Example 4:

Making the function case-sensitive using the COLLATE clause.

SELECT CHARINDEX
('A', 'There is always a need to Develop' COLLATE Latin1_General_CS_AS)
AS Found;

Output :

The function is now following a case-sensitive search, and since it doesn’t contain “A”, so the function will return 0.

Found
0


Next Article

Similar Reads