Lets say I have a table as such:
Column | Type | Notes
---------+------------ +----------------------------------------------------------
id | integer | An ID that's FK to some other table
seq | integer | Each ID gets its own seq number
data | text | Just some text, totally irrelevant.
id
+ seq
is a combined key.
What I'd like to see is:
ID | SEQ | DATA
----+------ +----------------------------------------------
1 | 1 | Quick brown fox, lorem ipsum, lazy dog, etc etc.
1 | 2 | Quick brown fox, lorem ipsum, lazy dog, etc etc.
1 | 3 | Quick brown fox, lorem ipsum, lazy dog, etc etc.
1 | 4 | Quick brown fox, lorem ipsum, lazy dog, etc etc.
2 | 1 | Quick brown fox, lorem ipsum, lazy dog, etc etc.
3 | 1 | Quick brown fox, lorem ipsum, lazy dog, etc etc.
3 | 2 | Quick brown fox, lorem ipsum, lazy dog, etc etc.
3 | 3 | Quick brown fox, lorem ipsum, lazy dog, etc etc.
3 | 4 | Quick brown fox, lorem ipsum, lazy dog, etc etc.
As you can see, a combination of id
and seq
is unique.
I'm not sure how to set up my table (or insert statement?) to do this. I'd like to insert id
and data
, resulting in seq
being a sub-sequence dependent on id
.
seq
reflects (or should reflect) the order in which the rows are inserted, I'd rather use atimestamp
that gets populated automatically and generate aseq
number on the fly when selecting the rows. – Dygertseq
unreliable if it's generated on-the-fly. What problem do you want to solve with this construct? (f.ex. if your only goal is to makeid, seq
pairs unique, a single sequence will do that -- in fact it'll makeseq
unique, but that impliesid, seq
pairs uniqueness) – Emlynnseq
column? Depending on its intended use there can be different approaches. One important question here is: is it OK to have gaps in the sequence (due to deleted rows or incomplete rolled back transactions)? If gaps are not OK, then it would be expensive to recalculate the sequence if it is persisted, which means that it may be better to generate it on the fly when needed. If gaps are OK, then single global sequence (standard auto-increment column) is enough. – Epochmakingseq
without gaps? Can there be updates and deletes? What is your current Postgres version? Is the table going to be small or big? How important is performance important? Concurrent access? Concurrent write access? A plainserial
column asseq
plus a view withrow_number() OVER (PARTITION BY id ORDER BY seq) AS seq
is probably your best bet: #24919052 – Aeroserial
is the way to go. – AeroMAX(seq)+1
. This may be problematic for environments with multiple connections. See my comment to answer below. – Danndanna