How to use the TRIM function to remove leading and trailing spaces from a string in MySQL
In MySQL, string processing is one of the most common operations. Processing spaces in strings is an operation we often perform. In actual development, we often need to remove spaces at the beginning and end of strings to ensure data accuracy and consistency. This article will introduce how to use the TRIM function to remove leading and trailing spaces from a string in MySQL, and provide corresponding code examples.
TRIM function is a string function in MySQL, used to remove spaces at the beginning and end of a string. It can remove spaces and other specified characters from both ends of the string. The basic syntax of the TRIM function is as follows:
TRIM([specified character] FROM string)
Among them, the specified character is an optional parameter. If no characters are specified, spaces at both ends of the string will be removed by default. If a character is specified, the character at both ends and in the middle of the string will be removed. Below we will demonstrate this process with an example.
Suppose we have a table named students, which contains a column of string type data named name. Now we want to remove the leading and trailing spaces in this column of data. First, we need to create this table and insert some data, the code is as follows:
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL
);
INSERT INTO students (name) VALUES
(' Alice'), ('Bob '), (' Carol '), (' David ');
After creating the table and inserting data, we can use the TRIM function to remove spaces at the beginning and end of the string. The sample code is as follows:
SELECT name, TRIM(name) AS trimmed_name
FROM students;
After executing the above code, we will get the following results:
name | trimmed_name |
---|---|
Alice | |
Bob | |
Carol | |
David |
FROM students;
trimmed_name | |
---|---|
Alice | |
Bob | |
Carol | |
David |
The above is the detailed content of How to use the TRIM function to remove leading and trailing spaces from a string in MySQL. For more information, please follow other related articles on the PHP Chinese website!