MySQL TRIM() Function

In MySQL, the TRIM() function returns a string with the specified leading and/or trailing characters removed.

If you only want to remove leading characters from a string, use the LTRIM(). If you only want to remove trailing characters from a string, use the RTRIM().

TRIM() Syntax

Here is the syntax of MySQL TRIM() function:

TRIM(str)
TRIM(remove_str FROM str)
TRIM({BOTH | LEADING | TRAILING} remove_str FROM str)

Here:

  • BOTH represents removing leading and trailing spaces
  • LEADING represents removing leading spaces
  • TRAILING represents removing trailing spaces
  • If not specified {BOTH | LEADING | TRAILING}, BOTH is default.

Parameters

str
Required. The string to be trimmed.
remove_str
Optional. The leading and/or trailing strings to remove. If remove_str is not specified , the default value is spaces.

Return value

The TRIM() function returns a string with the specified leading and/or trailing characters removed.

When the parameter NULL is , the NULL function will return NULL.

TRIM() Examples

Here are some examples of MySQL TRIM() function.

SELECT
    TRIM('   Hello   '),
    TRIM(BOTH FROM '   Hello   '),
    TRIM(LEADING FROM '   Hello   '),
    TRIM(TRAILING FROM '   Hello   '),
    TRIM('_' FROM '___Hello___'),
    TRIM(BOTH '_' FROM '___Hello___'),
    TRIM(LEADING '_' FROM '___Hello___'),
    TRIM(TRAILING '_' FROM '___Hello___'),
    TRIM('_#' FROM '_#_#_Hello_#_#'),
    TRIM(BOTH '_#' FROM '_#_#_Hello_#_#'),
    TRIM(LEADING '_#' FROM '_#_#_Hello_#_#'),
    TRIM(TRAILING '_#' FROM '_#_#_Hello_#_#')\G
                      TRIM('   Hello   '): Hello
            TRIM(BOTH FROM '   Hello   '): Hello
         TRIM(LEADING FROM '   Hello   '): Hello
        TRIM(TRAILING FROM '   Hello   '):    Hello
             TRIM('_' FROM '___Hello___'): Hello
        TRIM(BOTH '_' FROM '___Hello___'): Hello
     TRIM(LEADING '_' FROM '___Hello___'): Hello___
    TRIM(TRAILING '_' FROM '___Hello___'): ___Hello
         TRIM('_#' FROM '_#_#_Hello_#_#'): _Hello
    TRIM(BOTH '_#' FROM '_#_#_Hello_#_#'): _Hello
 TRIM(LEADING '_#' FROM '_#_#_Hello_#_#'): _Hello_#_#
TRIM(TRAILING '_#' FROM '_#_#_Hello_#_#'): _#_#_Hello