MySQL INSTR() Function
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,0if absent, orNULLif either input isNULL.
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 | 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 forsubstrinsidestr. By contrast,LOCATE(substr, str, pos)putssubstrfirst and supports a third starting-position argument. - Checking for
>= 0instead of> 0: BecauseINSTR()uses1-based indexing,0means not found. Filtering withINSTR(...) >= 0matches every non-NULL row. - Empty substring edge case:
INSTR('abc', '')returns1, not0. - NULL inputs: If either
strorsubstrisNULL,INSTR()returnsNULL.
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.
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.