SQL RTRIM()
The SQL RTRIM() function removes any trailing spaces (spaces at the end) from a specified string. This function is useful for cleaning up data and ensuring consistent formatting when working with text fields that might have extra spaces.
The RTRIM() function is supported across major SQL databases, including SQL Server, MySQL, PostgreSQL, and Oracle.
In this tutorial, we will go through SQL RTRIM() String function, its syntax, and how to use this function in SQL statements for string operations, with the help of well detailed examples.
Syntax of SQL RTRIM() Function
The basic syntax of the SQL RTRIM() function is:
RTRIM(string);
Each part of this syntax has a specific purpose:
- string: The text from which you want to remove trailing spaces. This can be a column, variable, or text literal.
The RTRIM() function returns the string with all trailing spaces removed.
Setup for Examples: Creating the Database and Table
We’ll create a sample users table with fields username and address to demonstrate the RTRIM() function examples.
1. First, create a new database called user_data:
CREATE DATABASE user_data;
2. Select the user_data database to work with:
USE user_data;
3. Create a table named users with the fields user_id, username, and address:
CREATE TABLE users (
user_id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50),
address VARCHAR(100)
);
4. Insert sample data into the users table to use with the RTRIM() function examples:
INSERT INTO users (username, address)
VALUES ('Alice ', '123 Maple Street '),
('Bob ', '456 Oak Avenue '),
('Charlie', '789 Pine Road');
