Skip to content
Home » SQL Server PATINDEX

SQL Server PATINDEX

SQL Server PATINDEX  function is a string function that returns the starting position of the first occurrence of a pattern in a specified expression.




Wildcard characters can be used with PATINDEX Functions. However, the % character must come before and follow pattern.

The Starting position of PATINDEX Function is 1.

Return type of PATINDEX :

bigint if expression is of the varchar(max) or nvarchar(max) data types otherwise int.

If pattern or expression is NULL then PATINDEX  function returns NULL and if pattern or expression is zero then it returns zero.

SYNTAX 

PATINDEX ( '%pattern%' , expression )

pattern
Is a character expression that contains the sequence to be found.

expression
Is an expression typically a column that is searched to find the specified pattern.

Lets loot at an example of PATINDEX Function in SQL Server.

Basic use of PATINDEX 

The following Query checks a short character string for the starting location of the characters  ‘SER’  and returns the location of character.

DECLARE @Str AS VARCHAR(30) = 'MICROSOFT SQL SERVER 2016'

SELECT  PATINDEX('%SER%', @Str) AS Result

Using wildcard characters with PATINDEX

The following Query uses % and _ wildcards to find the position at which the pattern ‘S’, followed by any one character and  ‘L’  starts in the specified string.

DECLARE @Str AS VARCHAR(30) = 'MICROSOFT SQL SERVER 2016'

SELECT  PATINDEX('%S_L%', @Str) AS Result

 

When pattern or expression is not found

Patindex function returns 0 when pattern or expression is not found in string.

DECLARE @Str AS VARCHAR(30) = 'MICROSOFT SQL SERVER 2016'

SELECT  PATINDEX('%2019%', @Str) AS Result




Also Read..

CHARINDEX()

LEN()

DATALENGTH()

SUBSTRING()

REPLACE()

REPLICATE()

 

Loading

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from SQL Skull

Subscribe now to keep reading and get access to the full archive.

Continue reading