MySQL Trim Function

The MySQL trim function is used to remove specified characters from the beginning and end of a string. The character which is usually removed is the space but you can instruct the trim function to remove any other characters, such as whitespace characters, if necessary.

Data from external sources may come with unnecessary characters attached to it. It is a good idea to use the MySQL trim function to remove these unwanted characters.

The MySQL trim function tutorial below explains.

MySQL Trim Function Syntax

The syntax for the MySQL trim function is shown below:

TRIM([{BOTH | LEADING | TRAILING} [remstring] FROM] string)

In the syntax above, remstring is the string that you want to remove from string.

Everything else is just a fancy way of saying that you can tell it to remove LEADING characters, TRAILING characters, or BOTH.

If you don't specify the characters to remove, the function will default to removing spaces. If you don't specify where, the function will default to removing from the beginning and end of the string.

The examples below will make it clearer.

MySQL Trim Example

Take a look at the MySQL trim function in use. The comments in the code tells what each SQL statement will return.

SELECT TRIM('   Tutorial Arena   '); -- gives 'Tutorial Arena'
SELECT TRIM(BOTH 'x' FROM 'xxxTutorialxxx'); -- gives 'Tutorial'
SELECT TRIM(LEADING 'x' FROM 'xxxTutorialxxx'); -- gives 'Tutorialxxx'
SELECT TRIM(TRAILING 'x' FROM 'xxxTutorialxxx'); -- gives 'xxxTutorial'

So as we just saw, we can remove spaces from the beginning and end of the string without any fancy keywords. We can also specify what we want to remove and if we want it to come from the beginning or the end of the string, or both.

He hope this tutorial on the MySQL trim function was helpful.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...