MySQL LOCATE() Function
MySQL LOCATE() Function
The LOCATE() function returns the 1-based position of the first match of a substring inside a string. Unlike INSTR(), it lets you pass an optional third argument to resume searching from a later character offset.
Syntax
LOCATE(substr, str)
LOCATE(substr, str, pos)
- substr: The substring (needle) to search for.
- str: The full source string (haystack).
- pos: Optional
1-based starting position for the search. - Return value:
1-based character index,0if not found, orNULLif any argument isNULL.
Notice the argument order: LOCATE(substr, str) puts the needle first and haystack second—the exact reverse of INSTR(str, substr).
Practical Example
In demo_orders, tracking_number values follow a segmented pattern like 'TRK-2026-0094'. You can find both the first hyphen and the second hyphen by feeding the first offset plus one into LOCATE().
SELECT
order_id,
tracking_number,
LOCATE('-', tracking_number) AS first_dash,
LOCATE('-', tracking_number, LOCATE('-', tracking_number) + 1) AS second_dash
FROM demo_orders
ORDER BY order_id;
| order_id | tracking_number | first_dash | second_dash |
|---|---|---|---|
| 201 | TRK-2026-0094 | 4 | 9 |
| 202 | EXPRESS-881-NY | 8 | 12 |
| 203 | LOCAL990 | 0 | 0 |
Row 203 has no hyphen, so first_dash is 0 and second_dash also evaluates to 0.
Common Mistakes & NULL Behavior
- Reversing arguments with INSTR(): Writing
LOCATE(email, '@')instead ofLOCATE('@', email)searches for the entire email inside'@'and returns0. KeepLOCATE(needle, haystack)straight fromINSTR(haystack, needle). - pos larger than string length: If
pos > CHAR_LENGTH(str),LOCATE()returns0without raising an error. - Empty substring behavior:
LOCATE('', 'abc')returns1, andLOCATE('', 'abc', 2)returns2(unlessposexceedsCHAR_LENGTH(str) + 1, which returns0). - NULL propagation: Passing
NULLforsubstr,str, orposreturnsNULL.
Frequently Asked Questions
How is LOCATE() different from POSITION()?
POSITION(substr IN str) is equivalent to the two-argument form LOCATE(substr, str). Only LOCATE() supports a third starting position pos.
Is LOCATE() case-sensitive?
It follows the column's collation. Under utf8mb4_0900_ai_ci, 'trk' matches 'TRK'. Cast to BINARY or use a _bin collation for case-sensitive matching.
What happens if pos is 0 or negative in LOCATE()?
In MySQL, passing pos <= 0 causes LOCATE() to return 0 because valid string positions start at 1.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.