Updated on 2026-11-06 GMT+08:00

locate

The locate function is used to find the position of substr in str, counting from 1. The search can start from a specified position using start_pos.

Syntax

locate(string <substr>, string <str>[, bigint <start_pos>]) 

Parameters

Parameter

Mandatory

Type

Description

substr

Yes

STRING

The substring to be matched. If the input is of type BIGINT, DOUBLE, DECIMAL, or DATETIME, it is implicitly converted to STRING type before evaluation.

str

Yes

STRING

The target string to be searched. If the input is of type BIGINT, DOUBLE, DECIMAL, or DATETIME, it is implicitly converted to STRING type before evaluation.

start_pos

No

BIGINT

Specifies the starting position for the search, starting from 1. When not specified, the default is 1.

Return Values

Returns a value of type INT.

  • If substr cannot be matched in str, 0 is returned.
  • If str or substr is NULL, NULL is returned.
  • If start_pos is NULL, 0 is returned.

Example Code

Find the position of string ab in string abhiab. Return 1.

select locate('ab', 'abhiab'); 

Start searching from the 2nd position. Return 5.

select locate('ab', 'abhiab', 2); 

If start_pos is NULL, 0 is returned.

select locate('ab', 'abhiab', null); 

Find the position of string hi in string hanmeimei and lilei. Return 0.

select locate('hi', 'hanmeimei and lilei');