Lesson

MySQL INSTR() Function

10 min reading
Free Course

MySQL INSTR() Function

The INSTR() function returns the 1-based index of the first occurrence of a substring inside another string. Developers rely on it to locate delimiters like '@' in emails or hyphens in order codes.

Syntax

INSTR(str, substr)
  • str: The full source string (haystack) to search inside.
  • substr: The substring (needle) to find.
  • Return value: 1-based character index of the match, 0 if absent, or NULL if either input is NULL.

Pay close attention to the parameter order: INSTR() puts the full string first and the search substring second.

Practical Example

Suppose you want to inspect customer emails in demo_customers to find the position of '@' before extracting domain names.

SELECT
    customer_id,
    email,
    INSTR(email, '@') AS at_position
FROM demo_customers
ORDER BY customer_id;
customer_id email at_position
1 maya@north.io 5
2 liam@cloud.dev 5
3 invalid-email 0
4 NULL NULL

Row 3 contains no '@' symbol, so INSTR() returns 0. You can pair INSTR(email, '@') > 0 with SUBSTRING() to extract clean usernames.

Common Mistakes & NULL Behavior

  • Swapping argument order with LOCATE(): INSTR(str, substr) searches for substr inside str. By contrast, LOCATE(substr, str, pos) puts substr first and supports a third starting-position argument.
  • Checking for >= 0 instead of > 0: Because INSTR() uses 1-based indexing, 0 means not found. Filtering with INSTR(...) >= 0 matches every non-NULL row.
  • Empty substring edge case: INSTR('abc', '') returns 1, not 0.
  • NULL inputs: If either str or substr is NULL, INSTR() returns NULL.

Frequently Asked Questions

What is the difference between INSTR() and LOCATE()?

INSTR(str, substr) puts the source string first and accepts only two arguments. LOCATE(substr, str, pos) puts the substring first and lets you start searching from offset pos.

Is INSTR() case-sensitive in MySQL?

No, unless at least one argument is a binary string or uses a case-sensitive (_cs) or binary (_bin) collation.

Does INSTR() count characters or bytes?

For character strings (utf8mb4), INSTR() returns the character position, so multibyte accents do not skew the index.

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