9

I have a users table in my mysql database with columns like id, age and gender. I have inserted around 500 records into it.

Now i need to interchange the gender for the records, i.e., replace male with female and female with male.

I thought to do it this way:

update users set gender='female' where gender='male';
update users set gender='male' where gender='female';

But as you can see, as soon as i run the first query, all the records will be updated with the gender set to 'female'.

How can i modify the query or shall i go another way?

5 Answers 5

14
update users set gender=case when gender='male' then 'female' else 'male' end where gender in ('male','female');
Sign up to request clarification or add additional context in comments.

Comments

6
UPDATE users SET gender='tmp' WHERE gender='male';

UPDATE users SET gender='male' WHERE gender='female';

UPDATE users SET gender='female' WHERE gender='tmp';

1 Comment

This answer updates the table records multiple times, check out the other ones to do it in one go
3

Combine two queries into one :-

update users set gender = if (gender='female', 'male', 'female');

2 Comments

assuming, you have a third gender, this could update rows, which you won't to be updated ;)
naturally this should be so ;) but there could be an 'undefined' state (if OP allows this case), when a user won't give any data about his gender (i.e. the field gender could be empty and your statement would manipulate this field). but +1 for using IF
3
update users set gender='fem' where gender='male';
update users set gender='male' where gender='female';
update users set gender='female' where gender='fem';

Comments

2
update users set gender='wasmale' where gender='male';
update users set gender='male' where gender='female';
update users set gender='female' where gender='wasmale';

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.