Skip to content
Advertisement

How to add value to SET field in mysql?

I have a table named user with a field of type SET named privs. The allowed values of this field are: ‘ADD’,’EDIT’,DELETE’,’ALL’.

What SQL query should I execute to add let’s say value ‘EDIT’ to the field privs for a given row? But only if there is not already such a value.

EDIT:

I tried: update user set privs=concat(privs,’EDIT’)

But I got an error: Data truncated for column ‘privs’ at row 1/

And after that not all rows has EDIT value in its privs field.

Advertisement

Answer

Looks like MySQL is okay with adding a second EDIT. It does, however, demand that the list is properly comma separated:

update  user
set     privs = concat(privs, if(length(privs)>0,',',''), 'EDIT')
where   id = 42

Example at SQL Fiddle.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement