CHARINDEX

Returns the starting position of a string inside another string.

See also PATINDEX, REGEXP_INSTR.

Syntax

CHARINDEX ( needle_string_expr , haystack_string_expr [ , start_location ] )

Parameters

Parameter

Description

needle_string_expr

String to find

haystack_string_expr

String to search within

start_location

An integer at which the search starts. This value is optional and when not supplied, the search starts at the beggining of needle_string_expr

Returns

Integer start position of a match, or 0 if no match was found.

If one of the parameters is NULL, then the return value is NULL.

Examples

For these examples, consider the following table and contents:

CREATE TABLE users (
    id INT,
    username TEXT,
    email TEXT,
    password TEXT
);

INSERT INTO users (id, username, email, password)
VALUES (1, 'john_doe', '[email protected]', 'password1'),
       (2, 'jane_doe', '[email protected]', 'password2'),
       (3, 'bob_smith', '[email protected]', 'password3'),
       (4, 'susan_jones', '[email protected]', 'password4');

Using CHARINDEX

SELECT CHARINDEX('john', username) FROM users;

Output:

charindex|
---------+
1        |
0        |
0        |
0        |