Re: Advice on implementing counters in postgreSQL

From: "Marco Bizzarri" <marco(dot)bizzarri(at)gmail(dot)com>
To: PgSQL-General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Advice on implementing counters in postgreSQL
Date: 2008-08-02 08:22:40
Message-ID: 3f0d61c40808020122i21c1317av16ac42b3921f6219@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Thanks for the advice, Craig.

I'm on a number of different PostgreSQL versions, ranging from 7.4 to
8.3, so I've to retain, where possible, compatibility with older
versions.

Is this better on a transaction/serialization point of view?

Regards
Marco

On Sat, Aug 2, 2008 at 10:19 AM, Craig Ringer
<craig(at)postnewspapers(dot)com(dot)au> wrote:
> 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
>

--
Marco Bizzarri
http://iliveinpisa.blogspot.com/

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Craig Ringer 2008-08-02 09:04:01 Re: Advice on implementing counters in postgreSQL
Previous Message Craig Ringer 2008-08-02 08:19:55 Re: Advice on implementing counters in postgreSQL