BigQuery · String function
BigQuery RTRIM
RTRIM(value[, characters]) removes trailing whitespace, or every trailing character found in the characters set: RTRIM('12.500', '0') returns 12.5. It works like TRIM but only on the end of the string.
RTRIM is TRIM restricted to the right side. Without a second argument it removes trailing whitespace, including tabs, newlines, carriage returns and Unicode spaces such as U+00A0, which is how you clean values from fixed-width files or \r\n line endings. With a second argument it removes trailing characters while they belong to that set; the second argument is a set of characters, not a substring: every leading or trailing character that appears anywhere in the set is removed, in any order.
That set behaviour matters for file extensions and suffixes: RTRIM('metrics.csv', '.csv') returns metri. To remove an exact suffix, use REGEXP_REPLACE with a $ anchor, or check ENDS_WITH and cut with LEFT.
For BYTES values the set is required. RTRIM replaces TRIM(TRAILING ... FROM ...), which BigQuery doesn't support.
Syntax
RTRIM(value1[, value2])Arguments and return value
| Argument | Description |
|---|---|
value1 | The STRING or BYTES value to trim. |
value2 | Optional set of characters (STRING) or bytes (BYTES) to remove from the end. Defaults to whitespace for STRING; required for BYTES. |
Returns: STRING or BYTES, the same type as value1.
Examples
Trailing whitespace and line endings
SELECT
CONCAT('[', RTRIM(' order 42 '), ']') AS trailing_spaces,
CONCAT('[', RTRIM('order 42\r\n'), ']') AS crlf;| trailing_spaces | crlf |
|---|---|
| [ order 42] | [order 42] |
Set semantics vs exact suffix
SELECT
RTRIM('12.500', '0') AS trailing_zeros,
RTRIM('metrics.csv', '.csv') AS trims_too_much,
REGEXP_REPLACE('metrics.csv', r'\.csv$', '') AS exact_suffix;| trailing_zeros | trims_too_much | exact_suffix |
|---|---|---|
| 12.5 | metri | metrics |
Remove trailing separators
SELECT RTRIM('gift,express,,', ',') AS tags;| tags |
|---|
| gift,express |
Common mistakes
- The second argument is a set of characters, not a substring: every leading or trailing character that appears anywhere in the set is removed, in any order.
RTRIM('metrics.csv', '.csv')returnsmetri. - Stripping zeros from decimals as text.
RTRIM('100', '0')returns1; only do this on values that contain a decimal point, or format numbers with FORMAT or CAST instead. - Using
TRIM(TRAILING ' ' FROM value). That syntax fails in BigQuery; writeRTRIM(value).
FAQ
How do I remove trailing spaces in BigQuery?
Use RTRIM(value). It also removes trailing tabs, newlines and carriage returns.
How do I remove a file extension in BigQuery?
Use REGEXP_REPLACE(file_name, r'\.[^.]+$', '') for any extension, or r'\.csv$' for one in particular. RTRIM would treat .csv as a set of characters.
Related
More string functions
All BigQuery string functions · All functions · BigQuery error messages
