We help IT Professionals succeed at work.

What's the difference between CHARINDEX and PATINDEX?

Hi All

Question for you:  What's the difference between CHARINDEX and PATINDEX?
The difference is not clear to me.

When I run the below script it returns the same values:

Declare @str varchar(100) = 'abcdefghigklmnopqrstuvwxyz_e'

/*
CHARINDEX
http://msdn.microsoft.com/en-us/library/ms186323.aspx
Searches an expression for another expression and returns its starting position if found. 
*/

-- Select the first e in a string
SELECT CHARINDEX('ef', @str)

-- Select the first e in a string, starting at the 10th character
SELECT CHARINDEX('e', @str, 10)

/*
PATINDEX
http://msdn.microsoft.com/en-us/library/ms188395

Turns the starting position of the first occurrence of a pattern in a specified expression, 
  or zeros if the pattern is not found, on all valid text and character data types. 
*/
  
SELECT PATINDEX('%efg%', @str)

Open in new window

They both return bigint's that are the starting values.

Full disclosure:  I'm studying for the 70-433 exam, and this is not a work-related question.
Comment
Watch Question

Paul JacksonSoftware Engineer
CERTIFIED EXPERT
Top Expert 2011
Commented:
Commented:
The PATINDEX function allows for using wildcard syntax in the pattern being searched for, where as the CHARINDEX function does not support wildcard character searches. Let's look at each one of these functions in a little more detail.

A good page to look at is here:
Differences between CharIndex and PatIndex and how to use them.
CERTIFIED EXPERT
Top Expert 2010
Commented:
More generally, PATINDEX searches for a pattern, while CHARINDEX searches for a substring.

So, it's not just wild cards.  For example, you can use PATINDEX to find the starting position for the first substring that consists of three consecutive digits:

PATINDEX('%[0-9][0-9][0-9]%', SomeColumn)

Sort of like "Regular Expressions Lite" :)
Jim HornSQL Server Data Dude
CERTIFIED EXPERT
Most Valuable Expert 2013
Author of the Year 2015

Author

Commented:
>PATINDEX can use wildcard characters, but CHARINDEX cannot.
Okay.  That I saw, but was wondering if it was any other difference.  Now I know.   Thanks.