Sql Server Patindex Function

SQL Server: PATINDEX Function

In this post explains how to use the PATINDEX function in SQL Server (Transact-SQL) with syntax and examples.

Description

In SQL Server (Transact-SQL), the PATINDEX functions returns the location of a pattern in a string. The search is not case-sensitive.

Syntax

The syntax for the PATINDEX function in SQL Server (Transact-SQL) is:

PATINDEX( '%pattern%', string )

Parameters or Arguments

pattern

The pattern that you want to find. pattern must be surrounded by % characters. Other wildcard characters can be used in pattern, such as:

Wildcard Explanation
% Allows you to match any string of any length (including zero length)
_ Allows you to match on a single character
[ ] Allows you to match on any character in the [ ] brackets (for example, [abc] would match on a, b, or c characters)
[^] Allows you to match on any character not in the [^] brackets (for example, [^abc] would match on any character that is not a, b, or c characters)

string

is the string to search within.

Note

  • The first position in string is 1.
  • If the pattern is not found in string, the PATINDEX function will return 0.

Applies To

The PATINDEX function can be used in the following versions of SQL Server (Transact-SQL):

  • SQL Server 2017, SQL Server 2016, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005

Example

Let's look at some SQL Server PATINDEX function examples and explore how to use the PATINDEX function in SQL Server (Transact-SQL).

For example:

SELECT PATINDEX('%T_e%', 'AODBA.com');
Output: 7

SELECT PATINDEX('%A%com', 'AODBA.com');
Output: 2

SELECT PATINDEX('%[aeiou]%', 'AODBA.com');
Output: 2        (matches on the first a, e, i, o, or u character found)

SELECT PATINDEX('%z%', 'AODBA.com');
Output: 0