Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
ClausesStatementsKeywordsExpressionsFunctionsIndexesPerformance Optimization

MySQL TRIM() Function

The `TRIM()` function in MySQL is used to remove unwanted whitespace or specific characters from the beginning and/or end of a string. It is particularly useful for cleaning up user input or data retrieved from databases.

Usage

The `TRIM()` function is typically used when you need to ensure that strings are free of leading or trailing spaces or other specified characters. It enhances data consistency and prepares strings for further processing or comparison.

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

In this syntax, `str` is the string to be trimmed, and `remstr` is the optional string of characters to remove. The default behavior is to remove spaces from both ends of `str`. If `remstr` is not found at the beginning or end of the string, `TRIM()` will return the original string unaltered.

Examples

1. Basic Trim

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

This example removes all leading and trailing spaces from the string, resulting in `Hello World`.

2. Trimming Specific Characters

sql
SELECT TRIM('x' FROM 'xxxHello Worldxxx') AS trimmed_string;

Here, the `TRIM()` function removes the character 'x' only from the beginning and end of the string, leaving `Hello World`. Characters in the middle of the string remain unchanged.

3. Using TRIM with Column Data

sql
SELECT TRIM(LEADING '0' FROM account_number) AS clean_account_number
FROM accounts;

Leading zeros are removed from the `account_number` column values in the `accounts` table, resulting in a cleaner numeric representation.

Tips and Best Practices

  • Default to spaces. Use `TRIM()` without specifying `remstr` to remove spaces, which is common in most applications.
  • Explicitly define removal direction. Specify `BOTH`, `LEADING`, or `TRAILING` to clarify which part of the string should be trimmed.
  • Combine with other string functions. Use `TRIM()` alongside other functions like `UPPER()` or `LOWER()` for comprehensive string manipulation.
  • Ensure data consistency. Apply `TRIM()` to standardize data before performing operations like comparisons or joins.
  • Performance considerations. Be mindful of potential performance impacts when using `TRIM()` on large datasets or within complex queries.
  • Handling multi-byte characters. `TRIM()` can handle multi-byte characters such as Unicode, making it suitable for international datasets.