Martin AJ
Martin AJ

Reputation: 6707

How can I remove all spaces in the beginning of the string?

I have a table like this:

// posts
+----+--------------+
| id |  subject     |
+----+--------------+
| 1  |    subject 1 |
| 2  | subject 2    |
| 3  |   subject 3  |
| 4  |  subject 4   |
| 5  | subject 5    |
+----+--------------+

I need to remove all spaces that are in the beginning of the subject column. Here is my current code:

UPDATE posts set subject = REPLACE(subject, ' ', '') WHERE 1;

And here is the current result:

+----+--------------+
| 1  | subject1     |
| 2  | subject2     |
| 3  | subject3     |
| 4  | subject4     |
| 5  | subject5     |
+----+--------------+

And here is the expected result:

+----+--------------+
| 1  | subject 1    |
| 2  | subject 2    |
| 3  | subject 3    |
| 4  | subject 4    |
| 5  | subject 5    |
+----+--------------+

See? Just the spaces that are in the beginning of the string should be removed. Noted that there is a thing in regex (I tested in PHP) ^ which is exactly what I'm looking for. But I don't know how should I use it in MySQL. Any idea?

Upvotes: 0

Views: 47

Answers (2)

Nitin Srivastava
Nitin Srivastava

Reputation: 36

Use trim () function

Update posts

set subject=trim(subject) where 1

Upvotes: 2

Vivek
Vivek

Reputation: 803

mysql> select ltrim('      abc');
+--------------------+
| ltrim('      abc') |
+--------------------+
| abc                |
+--------------------+

Upvotes: 2

Related Questions