MySQL UPDATE append data into column
Asked Answered
S

6

35

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?

Sunbonnet answered 24/12, 2012 at 11:36 Comment(1)
@FahimParkar I didn't realize I could have used SQL Fiddle, but did not wish to try something uncertain on a live website. Thank you.Sunbonnet
D
73

Try this Query:

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

Refer this sql fiddle demo.

Deanery answered 24/12, 2012 at 11:51 Comment(1)
SQL fiddle demo outputs error for me (both in FF and Chrome). Created another one: sqlfiddle.com/#!9/8385a3/1/0Keelung
A
10

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');
Abohm answered 24/12, 2012 at 11:42 Comment(0)
H
4

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 |
Hardcastle answered 24/12, 2012 at 11:41 Comment(0)
W
0

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

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:

select *
from tablename

Results:

|         yourcol |
|-----------------|
| sadsdhsomevalue |
|       somevalue |
Wootten answered 23/3, 2015 at 9:32 Comment(0)
H
0

For those requiring a prepared-statement option, this example may help:

update tablename set col1name = concat(ifnull(col1name,""), ?) WHERE table_id = ?;

Regular binding will work; in this case two variables: col1name and table_id. This could be handy in change/upate logs. No need of grabbing previous logs.

Hauler answered 28/9, 2023 at 15:22 Comment(0)
H
-1

why are you write ifnull function: it is obvious that if col1name1 is empty it concatenate to null means null+'a,b,c' simply 'a,b,c' set col1name = concat(ifnull(col1name,""), 'a,b,c') instead of this you can directly write set col1name = concat(col1name, 'a,b,c')

Herisau answered 10/12, 2018 at 15:1 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.