RTRIM()
SQL · String Functions
Theory
RTRIM(string) removes trailing spaces, the ones at the end, and leaves the start untouched. RTRIM('Asha ') returns 'Asha'. As with LTRIM, SQLite, Postgres and Oracle accept a second argument listing characters to remove, so RTRIM('Delhi..', '.') returns 'Delhi'. In MySQL use TRIM(TRAILING '.' FROM x) for anything other than spaces.
RTRIM is especially common with fixed-width data. A CHAR(10) column, or a mainframe or bank export file, pads short values with spaces to a fixed length, so 'Pune' may really be stored as 'Pune '. Some databases ignore trailing spaces when comparing, others do not, and the padding still shows up in LENGTH, in concatenation and in exported files. RTRIM before concatenating or exporting avoids gaps like 'Pune , India'. It is also used to remove trailing punctuation or separators left behind when building strings.
Why we use it
Trailing spaces are the most invisible kind of dirty data: you cannot see them on screen, yet they break joins, string building and exports. RTRIM removes them without touching leading characters that may matter.
When to use it
Use RTRIM for fixed-width or CHAR-padded values, and to drop trailing punctuation or separators. Use TRIM when both ends may be dirty, and LTRIM for the start only.
How it works
- Take the string (and optional characters to strip)
- Look at the last character
- Is it in the strip set (space by default)? Yes: Remove it and look at the new last one. No: Stop.
- The rest of the string is kept as is
- Return the right-trimmed string
Syntax
RTRIM(string)Example
SELECT RTRIM('Asha ');
-- 'Asha'Key points
- Only trims from the right side
- Leading spaces are kept: ' Pune ' becomes ' Pune'
- RTRIM(str, 'chars') works in SQLite, Postgres and Oracle
- Useful for cleaning fixed-width or CHAR-padded data
- MySQL needs TRIM(TRAILING 'x' FROM str) for non-space characters