PATINDEX() in SQL
Returns the starting position of the first occurrence of a pattern in a string. Uses pattern matching with wildcards.
Syntax
Return type
PATINDEX() Function Example
What is PATINDEX() in SQL?
The PATINDEX()
function in SQL returns the starting position of the first occurrence of a specified pattern within a given string. Unlike CHARINDEX()
, which searches for an exact substring, PATINDEX()
allows pattern matching with wildcards, making it more flexible for locating text fragments. It is a 1-based index function (starting position is 1) and is primarily supported in SQL Server. If the pattern is not found, PATINDEX()
returns 0. This function is particularly useful for searching within unstructured text, validating data formats, and extracting dynamic patterns in SQL queries.
Parameters:
pattern: Pattern to search for (must include wildcards %)
string: The string to search within
Example Use Cases:
-- Find position of first number
-- Find position of word starting with 'S'
-- Locate email pattern
Notes:
Behavior: Returns 0 if the pattern is not found, requires wildcards (%) in the pattern, and is case-insensitive by default.
Performance Considerations: More resource-intensive than simple CHARINDEX
Version Info: Primarily SQL Server function
Deprecated/Recommended Alternatives: REGEXP_INSTR for other DBMS
Error Handling:
Error: Returns NULL if either parameter is NULL
Recommendation: Use COALESCE for NULL handling if needed
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
REGEXP_INSTR
REGEXP_INSTR(str, pattern)
Returns NULL
PostgreSQL
SIMILAR TO
SIMILAR TO pattern
Returns NULL
SQL Server
PATINDEX
PATINDEX('%pat%', str)
Returns NULL
SQLite
REGEXP
REGEXP pattern
Returns NULL
BigQuery
REGEXP_INSTR
REGEXP_INSTR(str, pattern)
Returns NULL
Snowflake
REGEXP_INSTR
REGEXP_INSTR(str, pattern)
Returns NULL
Athena
REGEXP_INSTR
REGEXP_INSTR(str, pattern)
Returns NULL