Transact-SQL Reference

PATINDEX

Returns 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.

Syntax

PATINDEX ( '%pattern%' , expression )

Arguments

pattern

Is a literal string. Wildcard characters can be used; however, the % character must precede and follow pattern (except when searching for first or last characters). pattern is an expression of the short character data type category.

expression

Is an expression, usually a column that is searched for the specified pattern. expression is of the character string data type category.

Return Types

int

Remarks

PATINDEX is useful with text data types; it can be used in a WHERE clause in addition to IS NULL, IS NOT NULL, and LIKE (the only other comparisons that are valid on text in a WHERE clause).

If either pattern or expression is NULL, PATINDEX returns NULL when the database compatibility level is 70. If the database compatibility level is 65 or earlier, PATINDEX returns NULL only when both pattern and expression are NULL.

Examples
A. Use a pattern with PATINDEX

This example finds the position at which the pattern "wonderful" begins in a specific row of the notes column in the titles table.

USE pubs
GO
SELECT PATINDEX('%wonderful%', notes)
FROM titles
WHERE title_id = 'TC3218'
GO

Here is the result set:

----------- 
46          

(1 row(s) affected)

If you do not restrict the rows to be searched by using a WHERE clause, the query returns all rows in the table and reports nonzero values for those rows in which the pattern was found and zero for all rows in which the pattern was not found.

B. Use wildcard characters with PATINDEX

This example uses wildcards to find the position at which the pattern "won_erful" begins in a specific row of the notes column in the titles table, where the underscore is a wildcard representing any character.

USE pubs
GO
SELECT PATINDEX('%won_erful%', notes)
FROM titles
WHERE title_id = 'TC3218'
GO

Here is the result set:

------------
46

(1 row(s) affected)

If you do not restrict the rows to be searched, the query returns all rows in the table and reports nonzero values for those rows in which the pattern was found.

See Also

Data Types

String Functions