Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrement value in mysql but not negative

People also ask

How do I decrement in MySQL?

You can decrement value in MySQL with update command. With this, you can also restrict the value to not reach below 0. update yourTableName set yourColumnName = yourColumnName - 1 where yourColumnName > 0; To avoid the value to go below zero, you can use yourColumnName > 0.

How do you increment and decrement in SQL?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

What does <> mean in MySQL?

MySQLi For Beginners The symbol <> in MySQL is same as not equal to operator (!=). Both gives the result in boolean or tinyint(1). If the condition becomes true, then the result will be 1 otherwise 0.


Add another condition to update only if the field is greater 0

UPDATE table 
SET field = field - 1
WHERE id = $number
and field > 0

You could prevent the new value to drop below zero by using GREATEST(). If the value drops below zero, zero will always be greater than your calculated value, thus preventing any value below zero to be used.

UPDATE  table
SET     field = GREATEST(0, field - 1)
WHERE   id = $number

And on a side note: Please don't use mysql_* functions any more. They are deprecated and will eventually be removed from PHP. Use PDO or MySQLi instead.


The option using GREATEST will not work in newer MySQL versions, and the accepted answer can be unuseful if you want to update multiple fields instead of one. My solution for this problem is using IF:

UPDATE  table
SET     field = IF(field > 0, field - 1, 0)
WHERE   id = $number

UPDATE table SET field = case when (field - 1) >0 then (field - 1)
else field end
WHERE id = $number

 UPDATE `table_name` SET field = field-1 WHERE `id` = '".$id."' AND field > 0

Note: field's data-type should be an INTEGER.


if the field is int unsigned, below is the best:

UPDATE table 
SET field = field - 1
WHERE id = $number
and field > 0

# or
UPDATE  table
SET     field = IF(field > 0, field - 1, 0)
WHERE   id = $number