MySQL SUBSTRING_INDEX() Function
MySQL SUBSTRING_INDEX() Function
The SUBSTRING_INDEX() function extracts the portion of a string before a specified number of delimiter occurrences. Positive counts read from the left, while negative counts read from the right.
Syntax
SUBSTRING_INDEX(str, delim, count)
- str: The delimited input string.
- delim: The delimiter substring to search for (case-sensitive).
- count: Positive integer to return text to the left of the
count-th delimiter; negative integer to return text to the right of the|count|-th delimiter from the end. - Return value: Extracted segment,
''ifcount = 0, fullstrifdelimis not found, orNULLif any argument isNULL.
Nesting two SUBSTRING_INDEX() calls lets you isolate any middle token without writing complex LOCATE() math.
Practical Example
Suppose demo_customers stores email addresses and demo_orders stores three-part order_code strings like 'US-2026-881'. You can extract domains and middle year tokens cleanly.
SELECT
c.customer_id,
c.email,
SUBSTRING_INDEX(c.email, '@', -1) AS domain,
o.order_code,
SUBSTRING_INDEX(SUBSTRING_INDEX(o.order_code, '-', 2), '-', -1) AS order_year
FROM demo_customers c
JOIN demo_orders o ON o.customer_id = c.customer_id
ORDER BY c.customer_id;
| customer_id | domain | order_code | order_year | |
|---|---|---|---|---|
| 1 | maya@north.io | north.io | US-2026-881 | 2026 |
| 2 | liam@cloud.dev | cloud.dev | DE-2025-412 | 2025 |
| 3 | invalid | invalid | INTL900 | INTL900 |
Notice row 3: when '@' or '-' is absent from the string, SUBSTRING_INDEX() returns the entire original string unchanged!
Common Mistakes & NULL Behavior
- Delimiter matching is case-sensitive:
SUBSTRING_INDEX('a-X-b', 'x', 1)fails to match uppercase'X'and returns'a-X-b'. - Missing delimiter returns the full string: Never assume
SUBSTRING_INDEX(email, '@', -1)returns''on malformed emails; filter withWHERE email LIKE '%@%'first. - Zero count returns empty string:
SUBSTRING_INDEX('a,b,c', ',', 0)returns''. - NULL propagation: If
str,delim, orcountisNULL, the result isNULL.
Frequently Asked Questions
How do I get the Nth token from a delimited string?
Nest two calls: SUBSTRING_INDEX(SUBSTRING_INDEX(str, ',', n), ',', -1). Verify the string has at least n - 1 delimiters first so shorter rows do not repeat the last token.
What happens if delim is an empty string ''?
MySQL returns '' immediately when delim is ''.
Does SUBSTRING_INDEX() work in SQLite?
No. SUBSTRING_INDEX() is a MySQL-specific function not built into SQLite.
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.