Re: How to create "auto-increment" field WITHOUT a sequence object?

From: Ireneusz Pluta <ipluta(at)wp(dot)pl>
To: Dmitry Koterov <dmitry(dot)koterov(at)gmail(dot)com>
Cc: Postgres General <pgsql-general(at)postgresql(dot)org>
Subject: Re: How to create "auto-increment" field WITHOUT a sequence object?
Date: 2011-07-03 14:25:43
Message-ID: 4E107BE7.20405@wp.pl
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

W dniu 2011-06-30 20:20, Dmitry Koterov pisze:
> And I need as compact uniq_id generation (with minimum "holes") as it possible - this is a VERY
> important requirement (to export these values into external systems which accepts only IDs limited
> from 1 to 100000).
>
> So I cannot use sequences: sequence value is obviously not rolled back, so if I insert
> nextval(...) as uniq_id, I will have large holes (because of often transaction rollbacks) and
> exhaust 100000 uniq_ids very fast. How to deal with all this without sequences?

You may use dense_rank() (or even rank()) window function to map your sequence-with-gaps to a
no-gap-id which will be used for exports.

Consider this:

test=# select uniq_id_with_gaps, dense_rank() over (order by uniq_id_with_gaps) as
uniq_id_without_gaps from (select generate_series(1, 100, 7) as uniq_id_with_gaps) a;
uniq_id_with_gaps | uniq_id_without_gaps
-------------------+----------------------
1 | 1
8 | 2
15 | 3
22 | 4
29 | 5
36 | 6
43 | 7
50 | 8
57 | 9
64 | 10
71 | 11
78 | 12
85 | 13
92 | 14
99 | 15

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Chris Travers 2011-07-03 14:47:01 Re: How to create "auto-increment" field WITHOUT a sequence object?
Previous Message Dmitriy Igrishin 2011-07-03 14:10:08 Re: How to create "auto-increment" field WITHOUT a sequence object?