TRIM() Function in MySQL

TRIM() function in MySQL is used to clean up data. It is also used to remove the unwanted leading and trailing characters in a string.

Syntax :

TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str)

Parameter : This method accepts three-parameter as mentioned above and described below :

  • BOTH | LEADING | TRAILING : LEADING, TRAILING, or BOTH option to explicitly instruct the TRIM() function to remove leading, trailing, or both leading and trailing unwanted characters from a string .By default, the TRIM() function uses the BOTH option.
  • removed_str : It is a string which we want to remove. If not given, spaces will be removed.
  • str : It identifies the string from which we want to remove removed_str.

Returns : It returns a string that has unwanted characters removed.

Example-1 : TRIM() function to remove only leading spaces.

SELECT TRIM(LEADING FROM "    www.w3wiki.net    ") AS TrimmedString;

Output :

TrimmedString
www.w3wiki.net

Example-2 : TRIM() function to remove only trailing spaces.

SELECT TRIM(TRAILING FROM "    www.w3wiki.net    ") AS TrimmedString;

Output :

TrimmedString
www.w3wiki.net

Example-3 : TRIM() function to remove both leading and trailing spaces.

SELECT TRIM("    www.w3wiki.net    ") AS TrimmedString;

Output :

TrimmedString
www.w3wiki.net

Example-4 : TRIM() function with the table data

Table : Student_Details :

Student_Id Student_Name
101 Virat
103 Rohit
105 Sikhar
SELECT  TRIM(TRAILING FROM Student_Name) FROM Student_Details AS Trimmed_String;

Output :

TrimmedString
Virat
Rohit
Sikhar