MySQL SUBSTRING() Function
MySQL SUBSTRING() Function
The SUBSTRING() function returns a portion of a string starting at a 1-based character position. You can omit the length to read until the end of the string, or pass a negative starting offset to count from the right.
Syntax
SUBSTRING(str, pos)
SUBSTRING(str, pos, len)
SUBSTRING(str FROM pos [FOR len])
- str: Input string or text column.
- pos: 1-based character offset (
1starts at the first character;-1starts at the last character). - len: Optional character count to keep.
- Return value: Substring slice,
''ifposis0orlenis less than1, orNULLif any argument isNULL.
Because SUBSTRING() counts logical characters under utf8mb4, accented words and emoji never slice mid-byte. When you combine SUBSTRING() with INSTR() or LOCATE(), you can parse variable-length values such as email domains or URL paths cleanly.
Practical Example
Suppose you need both the three-digit area code and the domain portion of customer contact fields in demo_customers.
SELECT
customer_id,
phone,
SUBSTRING(phone, 1, 3) AS area_code,
email,
SUBSTRING(email, INSTR(email, '@') + 1) AS email_domain
FROM demo_customers
ORDER BY customer_id;
| customer_id | phone | area_code | email_domain | |
|---|---|---|---|---|
| 1 | 512-555-0194 | 512 | maya@north.io | north.io |
| 2 | 415-555-8821 | 415 | liam@cloud.dev | cloud.dev |
| 3 | NULL | NULL | no-at-sign | no-at-sign |
Notice row 3: because INSTR('no-at-sign', '@') returns 0, 0 + 1 becomes 1, so SUBSTRING() returns the whole string! Always guard dynamic offsets with WHERE INSTR(email, '@') > 0 before slicing.
Common Mistakes & NULL Behavior
- Zero-position returns empty string:
SUBSTRING('MySQL', 0, 2)returns''because1is the first valid position. - Unchecked INSTR() + 1 fallback: If a delimiter is missing,
INSTR(...) + 1evaluates to1and returns the entire string silently. - Using SUBSTRING() when LEFT() or RIGHT() is clearer: For simple prefix or suffix slicing,
LEFT(str, n)andRIGHT(str, n)read faster. - NULL propagation: Passing
NULLforstr,pos, orlenreturnsNULL.
Frequently Asked Questions
What is the difference between SUBSTRING(str, pos, len) and SUBSTRING(str FROM pos FOR len)?
They behave identically. The FROM ... FOR ... form follows ANSI SQL syntax, while the comma form is shorter and common in MySQL queries.
Can SUBSTRING() split by a delimiter directly?
No, SUBSTRING() requires numeric positions. Use SUBSTRING_INDEX(str, delim, count) when splitting directly on a delimiter.
Does SUBSTRING() return NULL if len exceeds the string length?
No. MySQL simply stops at the end of str and returns the remaining characters without padding spaces.
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.