Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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".

like image 932
santanu Avatar asked Mar 25 '09 09:03

santanu


People also ask

Which MySQL function can be used to add text to an existing value?

$sql = mysql_query("UPDATE ptb_messages SET subject = CONCAT(subject, 'newvalue') WHERE id='".


2 Answers

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%'; 
like image 191
Paul Dixon Avatar answered Sep 21 '22 23:09

Paul Dixon


UPDATE tablename SET fieldname = CONCAT("test", fieldname) [WHERE ...] 
like image 36
Ferdinand Beyer Avatar answered Sep 18 '22 23:09

Ferdinand Beyer