How to prepend a string to a column value in MySQL?

MysqlSql Update

Mysql Problem Overview


I need a SQL update statement for updating a particular field of all the rows with a string "test" to be added in the front of the existing value.

For example, if the existing value is "try" it should become "testtry".

Mysql Solutions


Solution 1 - Mysql

You can use the CONCAT function to do that:

UPDATE tbl SET col=CONCAT('test',col);

If you want to get cleverer and only update columns which don't already have test prepended, try

UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';

Solution 2 - Mysql

UPDATE tablename SET fieldname = CONCAT("test", fieldname) [WHERE ...]

Solution 3 - Mysql

Many string update functions in MySQL seems to be working like this: If one argument is null, then concatenation or other functions return null too. So, to update a field with null value, first set it to a non-null value, such as ''

For example:

update table set field='' where field is null;
update table set field=concat(field,' append');

Solution 4 - Mysql

That's a simple one

UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);

Solution 5 - Mysql

  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column1) where 1
  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column2) where 1
  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column2, 'newtring2') where 1

We can concat same column or also other column of the table.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsantanuView Question on Stackoverflow
Solution 1 - MysqlPaul DixonView Answer on Stackoverflow
Solution 2 - MysqlFerdinand BeyerView Answer on Stackoverflow
Solution 3 - MysqlbvidinliView Answer on Stackoverflow
Solution 4 - MysqlsoulmergeView Answer on Stackoverflow
Solution 5 - Mysqluser3419778View Answer on Stackoverflow