How to Trim Whitespace in MySQL
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
This guide covers various techniques to remove leading, trailing, and excessive internal whitespace from strings in MySQL databases.
The TRIM function in MySQL is used to remove unwanted characters from a string. By default, it removes spaces, but it can be configured to remove other characters.
SELECT TRIM(' your text here '); -- Removes spaces from both ends
SELECT TRIM(LEADING 'x' FROM 'xxHello Worldxx'); -- Removes leading characters
SELECT TRIM(TRAILING 'x' FROM 'xxHello Worldxx'); -- Removes trailing characters
RTRIM and LTRIM are specialized functions for removing whitespace from the right (end) and left (start) of a string, respectively.
SELECT RTRIM(' text with space at the end ');
SELECT LTRIM(' text with space at start');
To remove all spaces from a string, including between words, use the REPLACE function.
SELECT REPLACE('your text with spaces', ' ', '');
Apart from spaces, strings may contain tabs (\\t), newlines (\\n), and other whitespace characters. The REPLACE function can also handle these.
SELECT REPLACE('line1\\nline2', '\\n', ' '); -- Replace newline with space
SELECT REPLACE('word1\\tword2', '\\t', ''); -- Remove tabs
For more complex scenarios, like removing excessive internal spaces, use regular expressions with the REGEXP_REPLACE function (available from MySQL 8.0).
SELECT REGEXP_REPLACE('your text here', '\\\\s+', ' ');
Be aware that applying these functions to NULL values will return NULL. To handle this, use COALESCE or IFNULL to provide default values.
SELECT TRIM(COALESCE(column_with_null, ''));
For databases with frequent whitespace issues, consider creating a stored procedure that automates the trimming process for multiple columns or tables.
CREATE PROCEDURE AutoTrim()
BEGIN
UPDATE your_table SET your_column = TRIM(your_column);
-- Add more trimming logic here
END;
When importing data, include trimming functions in the LOAD DATA INFILE or INSERT statements to ensure data consistency from the start.
LOAD DATA INFILE 'path/to/your/file.csv'
INTO TABLE your_table
(column1, @var1)
SET column2 = TRIM(@var1);
Basedash is built as an AI-native BI platform, so teams can go from ad hoc SQL to trusted answers and dashboards quickly, without the overhead of traditional BI setup.
Written by
Senior Engineer at Basedash
Robert Cooper is a senior engineer at Basedash who builds full-stack product systems across SQL data infrastructure, APIs, and frontend architecture. His work focuses on application performance, developer velocity, and reliable self-hosted workflows that make data operations easier for teams at scale.
Basedash lets you build charts, dashboards, and reports in seconds using all your data.