In MySQL, how to remove the specific prefix from entire column’s value and update them?


It can be done by applying TRIM() function on the column along with MySQL UPDATE statement. The example below will make it more clear.

Example

Suppose, we have a table ‘Employee’ which have the prefix ‘Dept.’ with all the values of Column ‘Department’ as follows −

mysql> Select * from Employee;
+------+----------------+------------+----------------------+
| Id   | Name           | Address    | Department           |
+------+----------------+------------+----------------------+
| 100  | Raman          | Delhi      | IT Dept.             |
| 101  | Mohan          | Haryana    | History Dept.        |
| 102  | Shyam          | Chandigarh | ENGLISH Dept.        |
| 103  | Sukhjeet Singh | Patiala    | Computer Engg. Dept. |
| 104  | Bimal Roy      | Calcutta   | Computer Engg. Dept. |
+------+----------------+------------+----------------------+
5 rows in set (0.01 sec)

Now, the query below will remove the prefix ‘Dept.’ from column Department and also update the table.

mysql> Update Employee set Department = TRIM(Trailing 'Dept.' FROM Department);
Query OK, 5 rows affected (0.10 sec)
Rows matched: 5 Changed: 5 Warnings: 0

mysql> Select * from Employee;
+------+----------------+------------+-----------------+
| Id   | Name           | Address    | Department      |
+------+----------------+------------+-----------------+
| 100  | Raman          | Delhi      | IT              |
| 101  | Mohan          | Haryana    | History         |
| 102  | Shyam          | Chandigarh | ENGLISH         |
| 103  | Sukhjeet Singh | Patiala    | Computer Engg.  |
| 104  | Bimal Roy      | Calcutta   | Computer Engg.  |
+------+----------------+------------+-----------------+
5 rows in set (0.00 sec)

The result set above shows that there is no prefix ‘Dept.’ with the column values.

Monica Mona
Monica Mona

Student of life, and a lifelong learner

Updated on: 06-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements