These functions help clean up text by removing extra spaces from the start, end, or both sides of a string.
TRIM, LTRIM, RTRIM in SQL
TRIM([LEADING | TRAILING | BOTH] ' ' FROM string) LTRIM(string) RTRIM(string)
TRIM removes spaces from both sides by default or can be told to remove only from the start (LEADING) or end (TRAILING).
LTRIM removes spaces only from the start (left side) of the string.
RTRIM removes spaces only from the end (right side) of the string.
SELECT TRIM(' hello ');
SELECT LTRIM(' hello ');
SELECT RTRIM(' hello ');
SELECT TRIM(LEADING ' ' FROM ' hello ');
This query shows how each function removes spaces differently from the string ' apple '.
SELECT TRIM(' apple ') AS trimmed_both, LTRIM(' apple ') AS trimmed_left, RTRIM(' apple ') AS trimmed_right;
Spaces mean the normal space character (ASCII 32). Some databases allow trimming other characters by specifying them.
TRIM is more flexible and standard SQL, while LTRIM and RTRIM are simpler shortcuts.
Always check your database documentation as syntax can slightly differ.
Use TRIM to remove spaces from both sides of a string.
Use LTRIM to remove spaces only from the start (left side).
Use RTRIM to remove spaces only from the end (right side).