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.
LVL 66
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorAsked:
Who is Participating?
 
Patrick MatthewsConnect With a Mentor 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" :)
0
 
twolConnect With a Mentor 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.
0
 
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorAuthor 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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.