CHARINDEX() in SQL
Returns the starting position of a substring within a string. Position is 1-based (first character is position 1).
Syntax
Return type
CHARINDEX() Function Example
What is CHARINDEX() in SQL?
The CHARINDEX()
function in SQL returns the starting position of a specified substring within a given string. The position is 1-based, meaning the first character in the string is at position 1. This function is primarily used in SQL Server and Sybase, while other databases like MySQL and PostgreSQL use POSITION()
or INSTR()
for similar functionality. CHARINDEX()
is useful for searching text, extracting specific portions of a string, or performing conditional checks based on substring locations. If the substring is not found, the function returns 0.
Parameters:
substring: The string to search for
string: The string to search within
start_position: Optional starting position for search
Example Use Cases:
-- Find @ in email addresses
-- Extract domain from email
-- Validate string contains substring
Notes:
Behavior:Returns 0 if the substring is not found (1 in some DBMS), is case-sensitive in some DBMS, and start_position is optional.
Performance Considerations: Consider indexing for frequent searches
Version Info: Function name varies by DBMS
Deprecated/Recommended Alternatives: POSITION() or INSTR() in some 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
LOCATE() or POSITION()
LOCATE('a', 'text')
Returns NULL
PostgreSQL
POSITION()
RIGHT('Hello', 2)
Returns NULL
SQL Server
CHARINDEX()
CHARINDEX('a', 'text')
Returns NULL
SQLite
INSTR()
INSTR('text', 'a')
Returns NULL
BigQuery
STRPOS()
STRPOS('text', 'a')
Returns NULL
Snowflake
CHARINDEX() or POSITION()
CHARINDEX('a', 'text')
Returns NULL
Athena
STRPOS()
STRPOS('text', 'a')
Returns NULL