Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrement integer in postgres only if larger than a minimum

Tags:

postgresql

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

like image 772
Niels Kristian Avatar asked Jan 19 '15 18:01

Niels Kristian


People also ask

How do you decrement a value in SQL?

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.

What is int2 in PostgreSQL?

smallint = int2 = int16. integer = int4 = int32. largeint = int8 = int64. The single-digit types represent the number of "bytes" used to store.

What is int8 in PostgreSQL?

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.

What is Nextval in Postgres?

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.


2 Answers

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)

like image 73
Schwern Avatar answered Oct 12 '22 16:10

Schwern


Another way...

UPDATE stats SET counter = (
  CASE WHEN counter > 1 
  THEN (counter - 1) 
  ELSE 1 END
) WHERE id = 24235;
like image 42
Niels Kristian Avatar answered Oct 12 '22 17:10

Niels Kristian