Returns the position of the first occurrence of a substring within a string. Positions are 1-based.
Syntax
bigint locate(string <substr>, string <str>[, bigint <start_pos>])
Parameters
| Parameter | Required | Type | Description |
|---|---|---|---|
substr |
Yes | STRING | The substring to search for. |
str |
Yes | STRING | The string to search in. |
start_pos |
No | BIGINT | The position to start searching from. |
Return value
Returns a BIGINT value representing the position of substr in str.
Usage notes
-
If
substris found, returns the position of its first occurrence. Positions start at1. -
If
substris not found instr, returns0. -
If
strorsubstris null, returns null. -
If
start_posis null, returns0.
Examples
Example 1: Find the position of ab in abchelloabc. The substring starts at position 1.
-- Returns 1
SELECT locate('ab', 'abchelloabc');
Example 2: Search for a substring that does not exist. The function returns 0.
-- Returns 0
SELECT locate('hi', 'abc,hello,ab,c');
Example 3: Pass null as start_pos. The function returns 0.
-- Returns 0
SELECT locate('ab', 'abhelloabc', NULL);
Related functions
LOCATE is a string function. For other string search and conversion functions, see String functions.