MySQL RIGHT() Function
MySQL RIGHT() Function
The RIGHT() function returns a specified number of characters from the end of a string. It provides a clean shortcut for reading file extensions, last four phone digits, and trailing code segments.
Syntax
RIGHT(str, len)
- str: The source string or column.
- len: Number of trailing characters to extract.
- Return value: Substring of up to
lencharacters from the right, orNULLif either input isNULL.
Because RIGHT() measures characters instead of bytes, multibyte UTF-8 text stays intact even when cutting near accented letters.
Practical Example
Support dashboards often display only the last four digits of customer phone numbers and postal codes from demo_customers.
SELECT
customer_id,
phone,
CONCAT('***-***-', RIGHT(phone, 4)) AS masked_phone,
RIGHT(postal_code, 3) AS zone_suffix
FROM demo_customers
ORDER BY customer_id;
| customer_id | phone | masked_phone | zone_suffix |
|---|---|---|---|
| 1 | 512-555-0194 | --0194 | 701 |
| 2 | 415-555-8821 | --8821 | 107 |
| 3 | NULL | NULL | 021 |
When len exceeds the total character count of str, MySQL simply returns the entire string without padding.
Common Mistakes & NULL Behavior
- Zero or negative len returns empty string:
RIGHT('90210', 0)andRIGHT('90210', -2)both return'', never characters from the left. - Trailing spaces count as characters: If a column has trailing spaces (
'ABC '),RIGHT('ABC ', 2)returns' '. RunRTRIM()first if values come from padded exports. - Strict NULL propagation: If
strorlenisNULL,RIGHT()returnsNULL.
Frequently Asked Questions
How is RIGHT(str, n) related to SUBSTRING(str, -n)?
When n is positive and no larger than the string length, RIGHT(str, n) and SUBSTRING(str, -n) produce identical results.
Can I use RIGHT() to extract domain names from emails?
No, because domain lengths vary. Use SUBSTRING_INDEX(email, '@', -1) for variable-length suffixes after a delimiter.
Does RIGHT() work on integers without CAST()?
Yes. MySQL converts numbers to strings first, so RIGHT(20260415, 2) returns '15'.
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.