Applies to VAST Cluster 5.5.
Functions › Trimming and padding › Trimming and padding. Removes characters from the end (the right) of a string: spaces by default, or any of the characters you list. It's the same as trim(TRAILING characters FROM s).
Syntax
rtrim(s)
rtrim(s, characters)
| Argument | Type | Description |
|---|---|---|
s |
VARCHAR |
The string to trim. |
characters |
VARCHAR |
Optional. The set of characters to remove, in any order. Leave it out to remove spaces. |
Returns: VARCHAR.
Related: trim(TRAILING characters FROM s) does the same; ltrim trims the start and trim both ends.
Set up the examples
The examples connect with the ADBC driver, as in VAST Query Engine (ADBC), and work in a schema called docs_sql_fn_string_rtrim. Set QE_ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and VASTDB_BUCKET (SQL reference), and run the blocks in order in one Python session. Below each block is the output you should see.
This block connects, defines the run() and plan() helpers, and creates a table of five values read from text files: a status with trailing spaces, a decimal with trailing zeros, a directory with trailing slashes, and a line that still ends with a Windows line break (\r\n). The last row has no values:
import os
import re
import adbc_driver_manager
import adbc_driver_manager.dbapi as dbapi
import adbc_driver_vastdb
BUCKET = os.environ["VASTDB_BUCKET"]
SCHEMA = f'"{BUCKET}/docs_sql_fn_string_rtrim"'
conn = dbapi.connect(
driver=adbc_driver_vastdb.get_driver_path(),
db_kwargs={
"vast.db.endpoint": os.environ["QE_ENDPOINT"],
"vast.db.access_key": os.environ["AWS_ACCESS_KEY_ID"],
"vast.db.secret_key": os.environ["AWS_SECRET_ACCESS_KEY"],
},
autocommit=True,
)
def server_message(e):
"""The server's message in a driver error, without the request ID or the echoed statement."""
text = re.sub(r"\[req=0x[0-9a-f]+\]: ", "", str(e))
found = (re.search(r'message: "(.*?)", request_id', text, re.S)
or re.search(r"description: (.*)\)", text, re.S))
message = found.group(1) if found else text.strip().splitlines()[-1]
message = re.sub(r"^Plan query: '.*?' failed with: ", "", message, flags=re.S)
message = re.split(r"\\n|\n", message)[0].replace('\\"', '"')
return message.replace(BUCKET, "<bucket>")
def run(sql):
"""Run one statement. Print the rows it returns, or the error."""
try:
with conn.cursor() as cur:
cur.execute(sql)
rows = cur.fetchall() if cur.description else []
except (adbc_driver_manager.Error, OSError) as e:
print(f"{type(e).__name__}: {server_message(e)}")
else:
print(rows)
def plan(sql):
"""Print the plan without its ~N Rows lines: the table's row count, which can still be 0 just after an insert."""
with conn.cursor() as cur:
cur.execute("EXPLAIN " + sql)
steps = cur.fetchall()[0][1]
print("\n".join(line for line in steps.splitlines() if "Rows" not in line))
TABLE = f"{SCHEMA}.fields"
run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}")
run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, val VARCHAR)")
run(f"INSERT INTO {TABLE} VALUES "
"(1, 'done '), "
"(2, '12.500'), "
"(3, '/data/logs///'), "
"(4, 'last line\r\n'), "
"(5, NULL)")
[]
[]
[(5,)]
What it does
Without characters, rtrim(s) removes spaces from the end of the string, including Unicode spaces such as the no-break space (U+00A0), but not tabs or line breaks: rtrim('a\n'), rtrim('a\t') and rtrim('a\r\n') return the string unchanged. The start of the string is never touched: rtrim(' a ') returns ' a'.
With characters, rtrim(s, characters) removes every character in the set from the end, until it reaches one that isn't in the set. The set has no order and no wildcards, and the match is case-sensitive:
| Call | Result |
|---|---|
rtrim('1.500', '0') |
'1.5' |
rtrim('1.000', '.0') |
'1': the dot is in the set too |
rtrim('a/b///', '/') |
'a/b' |
rtrim('abc', 'cb') |
'a': the order of the set doesn't matter |
rtrim('xxa', 'x') |
'xxa': only the end is trimmed |
rtrim('', 'x'), rtrim('a', '') |
'', 'a': an empty set removes nothing |
The set is made of code points. A precomposed é is one code point, so rtrim('aé', 'é') returns 'a'. An é typed as e and a combining accent is two: rtrim('cafe\u0301', '\u0301') removes only the accent and returns 'cafe'.
NULLs and edge cases
| Input | Result |
|---|---|
s is NULL |
NULL |
characters is NULL |
NULL |
'' (empty string) |
'' |
rtrim('a\u00a0') (a no-break space) |
'a' |
rtrim('a\n'), rtrim('a\t'), rtrim('a\r\n') |
unchanged |
rtrim('cafe\u0301', '\u0301') |
'cafe' |
s a number, date, boolean, BLOB or list, or a number as characters |
Error: No function matches the given name and argument types |
The same cases, as the cluster returns them. They use the table and helpers from Set up the examples:
run("SELECT rtrim(NULL), rtrim('a', NULL), rtrim(NULL, 'x'), rtrim(''), rtrim('a\u00a0'), "
"rtrim('a\n'), rtrim('a\t'), rtrim('a\r\n')")
run("SELECT rtrim(' a '), rtrim('1.500', '0'), rtrim('1.000', '.0'), rtrim('a/b///', '/'), rtrim('abc', 'cb'), "
"rtrim('xxa', 'x'), rtrim('', 'x'), rtrim('a', '')")
run("SELECT rtrim('a\u00e9', '\u00e9'), rtrim('cafe\u0301', '\u0301')")
run("SELECT rtrim(42)")
[(None, None, None, '', 'a', 'a\n', 'a\t', 'a\r\n')]
[(' a', '1.5', '1', 'a/b', 'a', 'xxa', '', 'a')]
[('a', 'cafe')]
InternalError: Binder Error: No function matches the given name and argument types 'rtrim(INTEGER_LITERAL)'. You might need to add explicit type casts.
Examples
Remove trailing spaces, trailing zeros and trailing slashes. Row 4 keeps its line break unless you list \r and \n. The brackets show where each result ends:
run(f"SELECT id, rtrim(val) || ']', rtrim(val, '0'), rtrim(val, '/'), rtrim(val, '\r\n') || ']' "
f"FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 'done]', 'done ', 'done ', 'done ]'), (2, '12.500]', '12.5', '12.500', '12.500]'), (3, '/data/logs///]', '/data/logs///', '/data/logs', '/data/logs///]'), (4, 'last line\r\n]', 'last line\r\n', 'last line\r\n', 'last line]'), (5, None, None, None, None)]
Find a value whatever its trailing spaces:
run(f"SELECT id FROM {TABLE} WHERE rtrim(val) = 'done' ORDER BY id LIMIT 10")
[(1,)]
How it runs in VAST
The Query Engine runs on the cluster's CNodes, and a query on a table starts with a scan in VAST DataBase (VAST_SCAN). VAST DataBase can evaluate a comparison of a column with a constant, but not a function of a column, so rtrim() is always computed by the Query Engine:
- In the
SELECTlist, the scan reads the column and the Query Engine trims it for each row it returns. - In
WHERE, the scan sends the column for every row, and aFILTERstep in the Query Engine trims it and keeps the rows that match. No rows are skipped in storage.
The plan of the WHERE example shows the FILTER step above the scan:
plan(f"SELECT id FROM {TABLE} WHERE rtrim(val) = 'done'")
┌───────────────────────────┐
│ PROJECTION │
│ ──────────────────── │
│ #1 │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ FILTER │
│ ──────────────────── │
│ (rtrim(val) = 'done') │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ │
│ Projections: │
│ val │
│ id │
│ │
└───────────────────────────┘
Make it faster
- Trim when you write, not when you read. Remove trailing spaces and line breaks when you load the data, so that a query can compare the column with a constant,
val = 'done', and the comparison is pushed down to VAST DataBase. The plan of a raw column compared with a constant has noFILTERstep. - Combine it with a pushed-down condition. In
id < 3 AND rtrim(val) = 'done',id < 3is still evaluated in VAST DataBase, sortrim()runs only on the rows that pass it.
plan(f"SELECT id FROM {TABLE} WHERE val = 'done'")
┌───────────────────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ Projections: id │
│ │
└───────────────────────────┘
Limitations and errors
- Line breaks and tabs stay unless you list them.
rtrim(s)removes spaces only. To clean the end of a line read from a file, usertrim(s, ' \t\r\n'). - A set of characters, not a suffix.
rtrim(s, '.0')removes any mix of dots and zeros at the end, so it turns'100'into'1'as well as'1.000'. To drop the trailing zeros of a decimal, cast it to a number instead:CAST('1.500' AS DOUBLE). VARCHARonly. A number fails withNo function matches the given name and argument types 'rtrim(INTEGER_LITERAL)'. Cast it first:rtrim(CAST(x AS VARCHAR), '0').
run("SELECT rtrim('100', '.0'), rtrim('1.000', '.0'), CAST('1.500' AS DOUBLE), CAST('100' AS DOUBLE)")
run("SELECT rtrim(CAST(1.50 AS VARCHAR), '0')")
[('1', '1', 1.5, 100.0)]
[('1.5',)]
Similar functions
| Function | Removes | Result for 'xyaxy' and 'xy' |
|---|---|---|
rtrim(s, 'xy') |
the characters at the end | 'xya' |
ltrim (s, 'xy') |
the characters at the start | 'axy' |
trim (s, 'xy') |
the characters at both ends | 'a' |
trim(TRAILING 'xy' FROM s) |
the characters at the end | 'xya' |
regexp_replace (s, 'xy$', '') |
a suffix, once | 'xya' |
run("SELECT rtrim('xyaxy', 'xy'), ltrim('xyaxy', 'xy'), trim('xyaxy', 'xy'), trim(TRAILING 'xy' FROM 'xyaxy'), "
"regexp_replace('xyaxy', 'xy$', '')")
[('xya', 'axy', 'a', 'xya', 'xya')]
Clean up:
run(f"DROP TABLE IF EXISTS {TABLE}")
run(f"DROP SCHEMA IF EXISTS {SCHEMA}")
conn.close()
[]
[]
See also
- Trimming and padding: all the trimming and padding functions.
- trim, ltrim and rpad.
- Where filters run and pushdowns.
- EXPLAIN: how to read a plan.