SQL RTRIM Function Examples
Let’s see some examples of RTRIM function in SQL, and understand it’s working with examples of different use cases.
Example 1: Using RTRIM Function to Remove Trailing Spaces from a String
The RTRIM
function in SQL is used to remove trailing spaces from a string. Here are a few examples to illustrate its usage:
SELECT (' Geeks for Geeks ') as "Before RTRIM()",
RTRIM(' Geeks for Geeks ') as "After RTRIM()";
Output:
As we can see, the whitespaces in the right end of the string are removed, and the left side spaces remain as it is.
Example 2: Using RTRIM Function on Table Column
Suppose we have a table named Students with id and name. RTRIM() function will trim the trailing spaces in the given column.
First, we create a table GFG, with following commands.
CREATE TABLE GFG(
id integer,
name varchar(40));
INSERT INTO GFG VALUES
(1,"kiran "),
(2," navya ");
Output:
Now we will use RTRIM function on column name.
SELECT name as "Before RTRIM()", RTRIM(name) as "AFTER RTRIM()" from gfg;
Output:
The above query results in two columns, the first column represents the name column before using the RTRIM() function and the second column represents the values of name column after applying the RTRIM() function. As we can see, the trailing spaces are removed and width of the second column “AFTER TRIM()” is shortened.
Example 3: Using RTRIM Function With a Variable
DELIMITER //
CREATE PROCEDURE RTRIM_Example()
BEGIN
-- Declare a variable
DECLARE input_string VARCHAR(15);
-- Assign a value to the variable
SET input_string = 'Hello ';
-- Use the variable in a query
SELECT CONCAT(RTRIM(input_string), ' World') AS result;
END //
DELIMITER ;
-- Call the stored procedure
CALL RTRIM_Example();
Output:
We declare a variable in stored procedure and assign it a value. We changed delimiter to “//” to consider procedure as one statement. Then we use CONCAT function to concatenate declared variable and “World”.We have also use RTRIM function on declare variable in CONCAT function and As we can see in results, RTRIM method removed whitespace s from the declared variable.
SQL RTRIM() Function
SQL RTRIM function is a string function that removes spaces from the right side of a character or string. RTRIM or Right Trim function is used in data cleaning and manipulation in SQL.
In this example, we will learn the basics of the RTRIM function, and learn how it works with examples of different use cases.