Swadesh
Swadesh

Reputation: 651

How to write conditional update queries in Mysql?

I have a table users. I wish to update the column email based on some condition only.

update users set email='$email' where uid='$uid' 

(I wish to update the table users only if there is no other record containing the same email id)

Upvotes: 2

Views: 649

Answers (2)

Hassan
Hassan

Reputation: 1022

If there is not any restriction on not marking email field/column unique then you should probably do that. Then when a duplicate entry comes you will get an error which you can handle.

Otherwise if I understand your problem correctly, you need a query to update email given a UID and only if the email is not already in the table for any record. If thats the case then something like this should do:

update users
set email='$email'
where uid='$uid' and (select count(1) from users where email='$email') < 1

Hope this helps!

Upvotes: 0

Naveen Kumar Yadav
Naveen Kumar Yadav

Reputation: 432

While creating the table you need to make the email coloumn as an unique such that it will not allow you to insert duplicate values.Now you can use the above query such that there will be no email repeated in the table email coloumn

Upvotes: 2

Related Questions