How SQLite Rtrim() Works

In SQLite, the rtrim() function enables you to trim whitespace or other characters from the right part of a string.

It returns a copy of the string that you provide as an argument, with the right part trimmed of either whitespace, or other characters as specified.

Syntax

You can call rtrim() with either one or two arguments.

rtrim(X)
rtrim(X,Y)
  • If you provide one argument, this is the string to trim. In this case, whitespace is trimmed (if any) from the right of the string.
  • If you provide two arguments, the second argument contains the characters that are to be removed from the right of the string.

Trim Whitespace

Here’s an example to demonstrate how to trim whitespace from the right of a string.

.mode quote
SELECT rtrim(' Good Coffee ');

Result:

' Good Coffee'

In this example, only the right space is trimmed. The middle space remains intact, as is the space to the left of the string.

Note that the first line is not required for rtrim() to work.

In that line I’m simply setting the mode to output the resulting string surrounded by quotes. Doing this makes it easier to see the effect of rtrim().

Here it is without the rtrim() function:

SELECT ' Good Coffee ';

Result:

' Good Coffee '     

In this case, there’s still a space to the right of the string.

Multiple Spaces

If there are multiple spaces to the right of the string, rtrim() trims all of them.

SELECT rtrim('Good Coffee    ');

Result:

'Good Coffee'       

Trim Other Characters

As mentioned, rtrim() accepts an optional second argument that allows you to specify which character/s to trim from the string.

Here’s an example of using that syntax.

SELECT rtrim('!!!Beer!!!', '!');

Result:

'!!!Beer'          

This example also demonstrates that the left part of the string is left intact.

Below is another example. This time I specify more than one character to trim.

SELECT rtrim('Drink Beer!', ' Ber!');

Result:

'Drink'          

The characters don’t need to be in the same order that you provide in the argument. Here’s the same example, except that I switch the characters around in the second argument.

SELECT rtrim('Drink Beer!', '!er B');

Result:

'Drink'        

Case-Sensitivity

Be mindful of case-sensitivity. Here’s what happens if I change the case of one of the characters.

SELECT rtrim('Drink Beer!', ' ber!');

Result:

'Drink B'      

Trim Just the Left Part or Both Sides of the String

You can also use ltrim() to trim just the left part of the string, and trim() to trim both sides.