MySQL UPDATE append data into column

101
May 08, 2018, at 04:29 AM

I need to UPDATE tablename (col1name)

If there is already data, I need to append it with values 'a,b,c' If it is NULL, I need to add the values 'a,b,c'

I know there is a CONCAT argument, but not sure what the SQL syntax would be.

update tablename set col1name = concat(ifnull(col1name, 'a,b,c'), 'a,b,c')

Is the above correct?

Answer 1

Try this Query:

update tablename set col1name = concat(ifnull(col1name,""), 'a,b,c');

Refer this sql fiddle demo.

Answer 2

This should do it:

update tablename set
col1name = if(col1name is null, 'a,b,c', concat(col1name, 'a,b,c'));

Or you could make your life easier by doing it in two steps:

update tablename set col1name = '' where col1name is null;

then

update tablename set col1name = concat(col1name, 'a,b,c');
Answer 3

You can use the following:

update yourtable 
set yourcol = case when yourcol is null then 'a,b,c'
                  else concat(yourcol, ' a,b,c') end

See SQL Fiddle with Demo

Sample data:

CREATE TABLE yourtable(`yourcol` varchar(50));
INSERT INTO yourtable(`yourcol`)
VALUES  ('sadsdh'),
    (NULL);

Will return:

|      YOURCOL |
----------------
| sadsdh a,b,c |
|        a,b,c |
Answer 4

IFNULL(column,''), saves any if statements, makes the SQL much simpler!

SQL Fiddle

MySQL 5.6 Schema Setup:

CREATE TABLE tablename
    (`yourcol` varchar(50))
;
INSERT INTO tablename
    (`yourcol`)
VALUES
    ('sadsdh'),
    (NULL)
;
UPDATE tablename SET
    yourcol = CONCAT( IFNULL(yourcol,' '), 'somevalue' )
;

Query 1:

select *
from tablename

Results: | yourcol | |-----------------| | sadsdhsomevalue | | somevalue |

READ ALSO
PHP MYSQL select issues [on hold]

PHP MYSQL select issues [on hold]

I am having a problem joining my column and row value from my tables(res & rest)This is basically a simple reservation project

102
Mysql 5.6 Replication Lag fluctuating between 0 and n

Mysql 5.6 Replication Lag fluctuating between 0 and n

I have one master and 7 slavesDuring high load on my master, I see replication lag and it keeps fluctuating between 0 and n (where n keeps increasing with time and I have seen n grow more than 1 hour)

109
MYSQL QUERY with multiple options from a single table [duplicate]

MYSQL QUERY with multiple options from a single table [duplicate]

This question already has an answer here:

65
Will a read lock be released before upgrading to write lock?

Will a read lock be released before upgrading to write lock?

A deadlock is supposed to happen in below code snippet,but actually nothing happens:

79