The TRIM() function in MySQL is used to remove both leading and trailing spaces from a string. It is particularly useful for cleaning up strings that might have unwanted spaces at the beginning or end.
Syntax
TRIM(string)
Parameters
| Parameter | Description |
|---|---|
string |
Required. The string from which leading and trailing spaces will be removed. |
Definition and Usage
- The
TRIM()function removes the leading and trailing spaces from the specified string. It does not affect spaces within the string.
Return Values
- The function returns the string after removing any leading and trailing spaces.
Usage Examples
Example 1: Remove leading and trailing spaces from a string
SELECT TRIM(' SQL Tutorial ') AS TrimmedString;
Output:
| TrimmedString |
|---|
| SQL Tutorial |
Explanation: The function removes the spaces before and after the string SQL Tutorial.
Example 2: Using TRIM() with a column value
SELECT TRIM(CustomerName) AS TrimmedCustomerName
FROM Customers;
Output:
| TrimmedCustomerName |
|---|
| John Doe |
Explanation: The TRIM() function is applied to the CustomerName column to remove any leading or trailing spaces in the customer names.
Technical Details
- Works in: MySQL 4.0 and later.
- Return Type: String (the cleaned-up string without leading or trailing spaces).
Applications
- Data cleaning: Use
TRIM()to clean data before processing it, especially when working with user input or data from external sources where unwanted spaces may be added. - Formatting: Ensures that strings used in comparisons or further string manipulation are not affected by leading or trailing spaces.
Key Notes
- The
TRIM()function only removes spaces at the start and end of the string; it will not affect spaces within the string. - It can be useful when processing user inputs, CSV files, or data from external sources.