Open In App

SQL Server – PATINDEX() Function

The PATINDEX() function in the SQL server is used to return the starting index of the first occurrence of a pattern in a string or a specified expression. 

Syntax:

PATINDEX ( '%pattern%' , expression )

There are two parameters and both are required.



Applicable to:

The function PATINDEX() is applicable to the following databases.

Suppose if we want to find the first occurrence of ‘ek’ in the string ‘GeeksforGeeks’.then query will be like:



Query:

SELECT PATINDEX('%ek%', 'GeeksforGeeks');

Output:

3

 

Now if we finding the first occurrence of the letter ‘z’ in the string ‘GeeksforGeeks’.

Query:

SELECT PATINDEX('%[z]%', 'GeeksforGeeks');

Output:

It returns 0 because the given string does not contain the letter ‘z.

0

Take another example for finding the first occurrence of the symbol in the string ‘How are you?’.

Query:

SELECT position = PATINDEX('%[^ 0-9A-z]%', 'How are you?');

Output:

12

Article Tags :
SQL