Yuval
Yuval

Reputation: 514

How to do an atomic update and select query in mysql?

I have a table with three columns - id , name and num. I want to select id based on name if num is larger than 0 and decrement num in the same sql statement - how can I do it? I need to make sure somehow that these 2 statements :

select id from table where name='someValue' ; update table set num=num-1; 

would execute as atomic actions. How can I do that?

Upvotes: 2

Views: 1482

Answers (1)

Nesim Razon
Nesim Razon

Reputation: 9794

update table set num=num-1 where name='somevalue' and num>0

This query will decrease num by 1 if num is greater than 0 and name is equal to 'somevalue'

Upvotes: 1

Related Questions