We help IT Professionals succeed at work.
Get Started

What's the difference between CHARINDEX and PATINDEX?

3,091 Views
Last Modified: 2021-04-21
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
CERTIFIED EXPERT
Top Expert 2010
Commented:
This problem has been solved!
Unlock 3 Answers and 4 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE