0

My users table currently has a field sex which is either 1 or 2. I want to convert those values to "F" or "M" and put them into a different column. Is there any way to do this in mySQL?

I can write Ruby code to do this in the console, but I have on the order of 100K users and don't want to stall production while I loop.

3
  • you can use CASE WHEN Commented Dec 2, 2015 at 13:55
  • Do you mean you want to add an extra column to the table or do you just want to get F/M when you query the existing table. Commented Dec 2, 2015 at 13:57
  • I have a new column that should contain F/M while the original column contains 1/2 Commented Dec 2, 2015 at 14:38

2 Answers 2

1

You can do it in 3 steps

step 1 Add a new column into the table

alter table table_name add column sex_n char(1);

step 2 Write an update query

update table_name
set sex_n = case when sex = 1 then 'M' else 'F' end ;

step 3 Verify if the data is populated correctly then do

alter table table_name drop column sex
alter table table_name change sex_n sex char(1);

If you do not want an extra column you can use select to convert as

select
case when sex=1 then 'M'
else 'F'
end as sex 
from table_name
Sign up to request clarification or add additional context in comments.

2 Comments

Does the latter work if the sex column is type integer?
The last one is if you do not want to add another column into the table and using select you can modify and display, but the column will still contain 1 or 2 but while display via query it will show M or F
0

Query:

UPDATE tbl_name SET sex = (CASE WHEN sex = 1 THEN 'M' WHEN sex = 2 THEN 'F' ELSE '' END);

Add extra column with name gender then:

UPDATE tbl_name SET gender = (CASE WHEN sex = 1 THEN 'M' WHEN sex = 2 THEN 'F' ELSE '' END);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.