Lesson

MySQL LOCATE() Function

10 min reading
Free Course

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, 0 if not found, or NULL if any argument is NULL.

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 of LOCATE('@', email) searches for the entire email inside '@' and returns 0. Keep LOCATE(needle, haystack) straight from INSTR(haystack, needle).
  • pos larger than string length: If pos > CHAR_LENGTH(str), LOCATE() returns 0 without raising an error.
  • Empty substring behavior: LOCATE('', 'abc') returns 1, and LOCATE('', 'abc', 2) returns 2 (unless pos exceeds CHAR_LENGTH(str) + 1, which returns 0).
  • NULL propagation: Passing NULL for substr, str, or pos returns NULL.

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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum