Re: Update with a Repeating Sequence

From: Artacus <artacus(at)comcast(dot)net>
To:
Cc: pgsql-general General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Update with a Repeating Sequence
Date: 2008-10-15 04:45:06
Message-ID: 48F57552.30709@comcast.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Bill Thoen wrote:
> Steve Atkins wrote:
>>
>> On Oct 14, 2008, at 9:04 AM, Bill Thoen wrote:
>>
>>> I've got a table with repeated records that I want to make unique by
>>> adding a sequence code of 0,1,2,...,n for each set of repeated
>>> records. Basically, I want to turn:
>>> field_id | seq
>>> ----------+-----
>>> 1 | 0
>>> 2 | 0
>>> 3 | 0
>>> 3 | 0
>>> 3 | 0
>>> 4 | 0
>>> 4 | 0
>>> 5 | 0
>>> 6 | 0
>>> into:
>>> field_id | seq
>>> ----------+-----
>>> 1 | 0
>>> 2 | 0
>>> 3 | 0
>>> 3 | 1
>>> 3 | 2
>>> 4 | 0
>>> 4 | 1
>>> 5 | 0
>>> 6 | 0
>>>
>>> What's the best way to that?
>>
>> This is mildly tricky to do, and hard to maintain.
>>
>> In most cases where people say they need this, they're actually
>> perfectly happy with the seq value being enough to make the row
>> unique, and ideally increasing in order of something such as insertion
>> time ...

I know its academic now. But this is a great use case for the windowing
functions being added to 8.4. In 8.4 it should be as easy as

SELECT field_id, RANK() OVER(PARTITION BY field_id) AS seq
FROM foo;

Artacus

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Scott Marlowe 2008-10-15 05:26:55 Re: Column level triggers
Previous Message Tom Lane 2008-10-15 03:07:52 Re: Drupal and PostgreSQL - performance issues?