SQL - reduce the value to zero

I know how to increase / decrease a value in a column.

value type INT(11)

Team:

UPDATE table SET value = value - 1 WHERE id = 1

But when the value reaches "0", it continues to decrease.

Question: How to reduce to zero, so I do not get the value (-1) in the column?

Thanks for your code / ideas / suggestions

+4
source share
4 answers

Just use the conditional expression:

UPDATE table
    SET value = value - 1
    WHERE id = 1 AND value > 0;
+6
source

Add it to the where clause:

UPDATE table SET value = value - 1 WHERE (id = 1) AND (value > 0)

As soon as the value reaches 0, it will no longer be updated, because the sentence whereexcludes this entry from the update.

0
source

where where:

UPDATE table 
SET value = value - 1 
WHERE id = 1 and value >= 1
0

CASE.

UPDATE table SET value = CASE WHEN value = 1 THEN value = value - 1
ELSE value
END
WHERE id = 1
0

Source: https://habr.com/ru/post/1568344/


All Articles