I have a statement like this, that I use to decrement a counter:
UPDATE stats SET counter = counter - 1 WHERE id = 24235;
The problem is, that I never want the counter to go below 1
. How do I execute an update statement, that will only decrement down till 1
?
PG version 9.3
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.
smallint = int2 = int16. integer = int4 = int32. largeint = int8 = int64. The single-digit types represent the number of "bytes" used to store.
int8 is an alias for bigint . You can check for yourself - CREATE TABLE foo(bar int8); , then \d foo in psql. You'll see that column bar has type bigint.
NEXTVAL is a function to get the next value from a sequence. Sequence is an object which returns ever-increasing numbers, different for each call, regardless of transactions etc. Each time you call NEXTVAL , you get a different number. This is mainly used to generate surrogate primary keys for you tables.
UPDATE stats
SET counter = counter - 1
WHERE id = 24235
AND counter > 1;
If the decrementing amount varies, you have to make sure to pass in the same value in both places.
UPDATE stats
SET counter = counter - ?
WHERE id = ?
AND counter > ?;
Which you'd call with some pseudocode like sql.execute(decrement, id, decrement)
If the counter is never supposed to go below 1, I would add a constraint on that field. counter INTEGER CHECK (counter > 0)
Another way...
UPDATE stats SET counter = (
CASE WHEN counter > 1
THEN (counter - 1)
ELSE 1 END
) WHERE id = 24235;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With