In a PostgreSQL database I have a table with a primary key and another field which needs to be unique.
CREATE TABLE users (
id INTEGER PRIMARY KEY DEFAULT nextval('groups_id_seq'::regclass),
name VARCHAR(255) UNIQUE NOT NULL
);
INSERT users (name) VALUES ('foo');
INSERT users (name) VALUES ('foo');
INSERT users (name) VALUES ('bar');
The second insert fails but the sequence groups_id_seq is already incremented so when 'bar' is added it leaves a gap in the id numbers.
Is there a way to tell PostgreSQL to fetch the next value only if other constraints are met or should I check first using SELECT if the name is not duplicate? This still would not guarantee the lack of gaps but at least it would reduce their number to the rare cases when there is another process trying to insert the same name at the same time
NEXTVAL is a function to get the next value from a sequence. Sequence is an object which returns ever-increasing numbers, different for each call, regardless of transactions etc. Each time you call NEXTVAL , you get a different number. This is mainly used to generate surrogate primary keys for you tables.
The Oracle NEXTVAL function is used to retrieve the next value in a sequence. The Oracle NEXTVAL function must be called before calling the CURRVAL function, or an error will be thrown. No current value exists for the sequence until the Oracle NEXVAL function has been called at least once.
currval(' sequence_name ') Returns the most recently returned value from nextval(' sequence_name '). This value is associated with a PostgreSQL session, and if the nextval() function has not yet been called in the connected session on the specified sequence sequence_name , there will be no "current" value returned.
In this example, we will use the CREATE SEQUENCE statement to create a new ascending sequence starting from 10 with an increment of 5: CREATE SEQUENCE mysequence INCREMENT 5 START 10; To get the next value from the sequence to you use the nextval() function: SELECT nextval('mysequence');
I don't think so: a basic feature of sequences is that gaps are possible (think of two concurrent transactions, with one performing a ROLLBACK). You should ignore gaps. Why are they a problem in your case?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With