Re: Advice on implementing counters in postgreSQL - Mailing list pgsql-general

From Craig Ringer
Subject Re: Advice on implementing counters in postgreSQL
Date
Msg-id 489418AB.2010109@postnewspapers.com.au
Whole thread Raw
In response to Advice on implementing counters in postgreSQL  ("Marco Bizzarri" <marco.bizzarri@gmail.com>)
Responses Re: Advice on implementing counters in postgreSQL  ("Marco Bizzarri" <marco.bizzarri@gmail.com>)
List pgsql-general
Marco Bizzarri wrote:
> Hi all.
>
> I need to keep a numer of counters in my application; my counters are
> currently stored in a table:
>
> name | next_value | year
>
>
> The counters must be progressive numbers with no holes in between
> them, and they must restart from 1 every year. What I've done so far
> is to access them while in SERIALIZABLE ISOLATION LEVEL, with the
> following:
>
> SELECT next_value FROM counters WHERE name = 'name' for update;
> UPDATE counters SET next_value = next_value + 1 WHERE name = 'name';

If you're using a sufficiently recent version of Pg you can use:

UPDATE counters
SET next_value = next_value + 1
WHERE name = 'name'
RETURNING next_value;

instead, which is slightly nicer. It'll return the *new* value of
`next_value', so you'd have to make a few tweaks.

--
Craig Ringer

pgsql-general by date:

Previous
From: Craig Ringer
Date:
Subject: Re: Is there any reason why "edit PostgreSQL.conf should be on my menu"
Next
From: "Marco Bizzarri"
Date:
Subject: Re: Advice on implementing counters in postgreSQL