Friday, December 20, 2024

MySQL TRIM() Function

 The TRIM() function in MySQL is used to remove specified prefixes or suffixes (usually spaces) from a string. By default, it removes leading and trailing spaces from the string.

Syntax:

TRIM([remstr] FROM str)
  • remstr (optional): The characters to remove from the string. If not specified, it defaults to removing spaces.
  • str: The string from which the characters will be removed.

Example 1: Remove leading and trailing spaces

SELECT TRIM('   Hello World!   ') AS trimmed_string;

Result:

trimmed_string
----------------
Hello World!

Example 2: Remove specific characters

You can remove specific characters from the beginning and end of a string. For example, removing dashes (-):

SELECT TRIM('-' FROM '--Hello World!--') AS trimmed_string;

Result:

trimmed_string
----------------
Hello World!

Example 3: Removing spaces from both ends

SELECT TRIM(' ' FROM '   Hello World!   ') AS trimmed_string;

Result:

trimmed_string
----------------
Hello World!

Notes:

  • TRIM() only removes characters from the beginning and end of the string, not from the middle.
  • To remove characters from the middle of the string, use the REPLACE() function.

No comments:

Post a Comment