MySQL RTRIM()
In SQL language, the RTRIM() function allows you to delete characters at the end of a string. Most often the RTRIM() function is used to remove invisible characters, i.e. characters such as space, tab, line feed or even carriage return. Such a function can be useful to save space in a database or to display data properly.
Syntax:
The most common use is to remove the invisible characters at the end of a string using the following syntax:
SELECT RTRIM(' Example ');
The output of this function allows to get only the word " Example"
without the end spaces.
If you want to delete the whitespace at the beginning of a string use the LTRIM() function.
Example :
Let’s assume a table that has any type of message. These messages can contain spaces or line breaks at the beginning and end of the string.
+----------+------------+---------------------------------------+ | id | date | message | +----------+------------+---------------------------------------+ | 1 | 01-03-1993 | 819 Saint Francis Way | | | | | +----------+------------+---------------------------------------+ | 2 | 11-12-2001 | 171 Jarvisville Road Michigan | +----------+------------+---------------------------------------+ | | | | | 3 | 05-06-2004 | 188 Clay Street Indiana | | | | | +----------+------------+---------------------------------------+
It is possible to use a query to get the id, the date, and the message without the invisible characters at the end. The following SQL query allows to remove the spaces from the “message” column:
SELECT id, date, RTRIM(message) AS message_trimed FROM messages
Output:
+----------+------------+-----------------------------------+ | id | date | message_trimed | +----------+------------+-----------------------------------+ | 1 | 01-03-1993 | 819 Saint Francis Way | +----------+------------+-----------------------------------+ | 2 | 11-12-2001 | 171 Jarvisville Road Michigan | +----------+------------+-----------------------------------+ | | | | | 3 | 05-06-2004 | 188 Clay Street Indiana | +----------+------------+-----------------------------------+
There are 2 other very similar functions to delete characters at the beginning and end of a string.