How to Remove Leading Whitespace in MySQL

MySQL has the LTRIM() function that enables you to remove leading whitespace from a string (space at the start of the string).

MySQL also has the TRIM() function that enables you to remove leading space, trailing space (at the end), space from both sides, or to remove other specified characters from either side (or both sides) of the string.

This article demonstrates how to remove leading space using each of these functions.

Example – LTRIM()

Here’s a basic example of removing whitespace from the start of a string:

SELECT LTRIM('     Joe Satriani     ') AS Trimmed;

Result:

+-------------------+
| Trimmed           |
+-------------------+
| Joe Satriani      |
+-------------------+

The leading space is removed but the trailing space remains.

Here’s what it looks like when compared to the untrimmed string:

SELECT 
    LTRIM('     Joe Satriani     ') AS Trimmed,
    '     Joe Satriani     ' AS Untrimmed;

Result:

+-------------------+------------------------+
| Trimmed           | Untrimmed              |
+-------------------+------------------------+
| Joe Satriani      |      Joe Satriani      |
+-------------------+------------------------+

Example – TRIM()

Here’s an example of doing the same thing, but using the TRIM() function:

SELECT TRIM(LEADING ' ' FROM '     Joe Satriani     ') AS Trimmed;

Result:

+-------------------+
| Trimmed           |
+-------------------+
| Joe Satriani      |
+-------------------+

Only the leading space is removed – the trailing space remains. This is because we use the LEADING specifier.

Other Uses of TRIM()

You can also use TRIM() to remove trailing space (simply replace LEADING with TRAILING), as well as to remove space from both sides (replace LEADING with BOTH).

Also, you aren’t just limited to spaces. TRIM() can be used to remove other characters too.