SQL Server String RTRIM() Function



SQL Server RTRIM() Function

The SQL Server RTRIM() function is used to remove trailing spaces from a string. This function is useful for cleaning up string data by eliminating unwanted spaces at the end of the string.


Syntax

SELECT RTRIM(string);

The RTRIM() function takes a single argument:

  • string: The string from which to remove trailing spaces.

Example SQL Server RTRIM() Function Queries

Let's look at some examples of SQL Server RTRIM() function queries:

1. Basic RTRIM() Example

SELECT RTRIM('Hello World   ') AS result;

This query removes the trailing spaces from the string 'Hello World '. The result will be:

result
-------------
Hello World

2. RTRIM() with a Column

SELECT first_name, RTRIM(first_name) AS trimmed_first_name
FROM employees;

This query removes the trailing spaces from the first_name column for each employee. The result will show the first_name and the trimmed version as trimmed_first_name.

3. RTRIM() with a Variable

DECLARE @myString VARCHAR(50);
SET @myString = 'SQL Server   ';
SELECT RTRIM(@myString) AS result;

This query uses a variable to store a string and then removes the trailing spaces. The result will be:

result
-----------
SQL Server

Full Example

Let's go through a complete example that includes creating a table, inserting data, and using the RTRIM() function.

Step 1: Creating a Table

This step involves creating a new table named example_table to store some sample data.

CREATE TABLE example_table (
    id INT PRIMARY KEY,
    description VARCHAR(50)
);

In this example, we create a table named example_table with columns for id and description.

Step 2: Inserting Data into the Table

This step involves inserting some sample data into the example_table.

INSERT INTO example_table (id, description) VALUES (1, 'Apple   ');
INSERT INTO example_table (id, description) VALUES (2, 'Banana  ');
INSERT INTO example_table (id, description) VALUES (3, 'Cherry  ');

Here, we insert data into the example_table.

Step 3: Using the RTRIM() Function

This step involves using the RTRIM() function to remove trailing spaces from the description column.

SELECT id, description, RTRIM(description) AS trimmed_description
FROM example_table;

This query retrieves the id, description, and the trimmed version of the description column for each row in the example_table. The result will be:

id  description  trimmed_description
--- ------------ --------------------
1   Apple        Apple
2   Banana       Banana
3   Cherry       Cherry

Conclusion

The SQL Server RTRIM() function is a powerful tool for removing trailing spaces from a string. Understanding how to use the RTRIM() function and its syntax is essential for effective string manipulation and data processing in SQL Server.