MySQL RTRIM() Function
MySQL RTRIM() Function
The RTRIM() function removes all trailing ASCII space characters (' ') from the right side of a string. Leading spaces and interior spaces inside the text stay unchanged.
Syntax
RTRIM(str)
- str: The string expression or column to trim on the right.
- Return value: String with trailing spaces removed, or
NULLwhenstrisNULL.
RTRIM() becomes especially important in MySQL 8.0+ because modern utf8mb4_0900_ai_ci collations use NO PAD comparison rules, meaning trailing spaces affect WHERE equality checks.
Practical Example
Legacy HR imports in demo_employees sometimes store padded department names. Here is how RTRIM() strips trailing spaces before grouping or matching records.
SELECT
employee_id,
CONCAT('[', department, ']') AS raw_dept,
CONCAT('[', RTRIM(department), ']') AS trimmed_dept,
CHAR_LENGTH(RTRIM(department)) AS clean_len
FROM demo_employees
ORDER BY employee_id;
| employee_id | raw_dept | trimmed_dept | clean_len |
|---|---|---|---|
| 1 | [Sales ] | [Sales] | 5 |
| 2 | [ Ops ] | [ Ops] | 6 |
| 3 | [ ] | [] | 0 |
| 4 | NULL | NULL | NULL |
Row 2 shows that RTRIM() removes the two trailing spaces after 'Ops' while preserving the two leading spaces.
Common Mistakes & NULL Behavior
- Only ASCII spaces are trimmed:
RTRIM()does not remove trailing tabs (), newlines (), or carriage returns (). Wrap withREPLACE()orREGEXP_REPLACE()for control characters. - No custom character parameter: MySQL's
RTRIM(str)takes one argument only. To strip trailing slashes or zeros, useTRIM(TRAILING '/' FROM path)instead. - NO PAD collation surprises: Under
utf8mb4_0900_ai_ci,'Sales 'does not equal'Sales'. Clean imported rows withRTRIM()during ingestion so lookups match reliably. - NULL input:
RTRIM(NULL)returnsNULL.
Frequently Asked Questions
What is the difference between RTRIM() and TRIM()?
RTRIM() strips trailing spaces only. TRIM() strips both leading and trailing spaces by default and also supports custom characters.
Does RTRIM() affect CHAR(n) columns?
MySQL automatically strips trailing spaces when retrieving CHAR(n) values anyway, so RTRIM() mainly helps on VARCHAR and TEXT columns.
Does RTRIM() turn a string of spaces into NULL?
No. RTRIM(' ') returns an empty string '' with length 0.
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.