MySQL has an RTRIM()
function that enables you to remove trailing whitespace from a string (space at the end of the string).
MySQL also has the TRIM()
function that enables you to remove trailing space, leading space (at the start), space from both sides, or to remove other specified characters from either side (or both sides) of the string.
This article demonstrates how to remove trailing space using each of these functions.
Example – RTRIM()
Here’s a basic example of removing whitespace from the end of a string:
SELECT RTRIM(' Joe Satriani ') AS Trimmed;
Result:
+-------------------+ | Trimmed | +-------------------+ | Joe Satriani | +-------------------+
The trailing space is removed but the leading space remains.
Here’s what it looks like when compared to the untrimmed string:
SELECT RTRIM(' Joe Satriani ') AS Trimmed, ' Joe Satriani ' AS Untrimmed;
Result:
+-------------------+------------------------+ | Trimmed | Untrimmed | +-------------------+------------------------+ | Joe Satriani | Joe Satriani | +-------------------+------------------------+
Example – TRIM()
Here’s an example of doing the same thing, but using the TRIM()
function:
SELECT TRIM(TRAILING ' ' FROM ' Joe Satriani ') AS Trimmed;
Result:
+-------------------+ | Trimmed | +-------------------+ | Joe Satriani | +-------------------+
Only the trailing space is removed – the leading space remains. This is because we use the TRAILING
specifier.
Other Uses of TRIM()
You can also use TRIM()
to remove leading space (simply replace TRAILING
with LEADING
), as well as to remove space from both sides (replace TRAILING
with BOTH
).
Also, you aren’t just limited to spaces. TRIM()
can be used to remove other characters too.