Skip to content
Advertisement

Recode column values in MySQL

I am dealing with a column named UCODE130 that has values anywhere from 1-130. I would like to replace the values with ranges. For example, I want to replace any 1, 2, 3, or 4 found in that column with a string “1 – 4” instead. I do not want to do just a select statement – I want to actually change the column in the database itself.

The other issue I have is that these ranges are all different sizes. I would need something like:

1,2,3,or 4 becomes “1 – 4”

5,6 becomes “5 – 6”

7,8,9,10,11,or 12 becomes “7 – 12”

and so on.

I need to recode or “find and replace” the values to get this to work. There are over 20,000 rows in my column so I was hoping there was an efficient way to do this. Please let me know if more information is needed. Thank you!

Advertisement

Answer

You can define the sizes with a CASE expression in the UPDATE statement:

or:

Note that for this to work the column’s data type must be VARCHAR.
If it is INTEGER, first change its data type:

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