Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql replace values in a table

Tags:

mysql

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?

like image 274
shasi kanth Avatar asked Dec 06 '11 13:12

shasi kanth


People also ask

How do you replace something in MySQL?

MySQL REPLACE() FunctionThe REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: This function performs a case-sensitive replacement.

How do I replace a word in a MySQL table?

Use the MySQL REPLACE() function to replace a substring (i.e. words, a character, etc.) with another substring and return the changed string. This function takes three arguments: The string to change.


1 Answers

update users set gender=case when gender='male' then 'female' else 'male' end where gender in ('male','female');
like image 54
rabudde Avatar answered Oct 19 '22 18:10

rabudde