Question

I had a quick question on serial data types used on primary key on informix db's.

If I delete a row, will the serial key carry on counting or will it re-adjust for any rows that were deleted?

So if current row is serial no 5, I delete number row withs serial no 3, will the next value be 6 and keep carrying on? Is serial no 3 that is now deleted forever lost not to be used again?

Was it helpful?

Solution

The counter used by SERIAL, SERIAL8 or BIGSERIAL is monotonically increasing until it wraps around. Deleted values are simply deleted. If you insert a literal value that is larger than the counter, the counter is adjusted so that the next inserted value is one bigger:

CREATE TABLE s (s SERIAL(2) NOT NULL PRIMARY KEY, v VARCHAR(20) NOT NULL);

INSERT INTO s(s,v) VALUES(0, "Row 2");
INSERT INTO s(s,v) VALUES(0, "Row 3");
INSERT INTO s(s,v) VALUES(0, "Row 4");
INSERT INTO s(s,v) VALUES(0, "Row 5");
DELETE FROM s WHERE s = 3;
INSERT INTO s(s,v) VALUES(0, "Row 6");
INSERT INTO s(s,v) VALUES(8, "Row 8"); -- Skip 7
INSERT INTO s(s,v) VALUES(0, "Row 9");

SELECT * FROM s ORDER BY s;

This generates the results:

          2     Row 2
          4     Row 4
          5     Row 5
          6     Row 6
          8     Row 8
          9     Row 9

All the types behave similarly. If you reach the maximum (2^32-1 for SERIAL, 2^63-1 for SERIAL8 and BIGSERIAL), then the counter wraps back to zero, but you may run into problems with unvacated spaces being reused and the primary key rejected the duplicate rows. Generally, avoid wrapping them. (It takes quite a while to make them wrap, especially the 64-bit counters.)

Note that you can manually insert a 'missing' value - such as 3 or 7. However, IDS will not do that for you.

@iQ asked:

So does Informix automatically re-use the unused or deleted serial values when it wraps around?

Not really. The value wraps back to 1; if the row with value 1 exists, the insert fails; if it doesn't, it succeeds; either way, the next attempt will try 2. To illustrate, continuing where the last example left off:

INSERT INTO s(s,v) VALUES(2147483647, "Row 2,147,483,647");
INSERT INTO s(s,v) VALUES(0, "Row next")     { 1 - Pass };
INSERT INTO s(s,v) VALUES(0, "Row next + 1") { 2 - Fail };
INSERT INTO s(s,v) VALUES(0, "Row next + 2") { 3 - Pass };
INSERT INTO s(s,v) VALUES(0, "Row next + 3") { 4 - Fail };
SELECT * FROM s ORDER BY s;

The end result is:

          1     Row next            
          2     Row 2               
          3     Row next + 2        
          4     Row 4               
          5     Row 5               
          6     Row 6               
          8     Row 8               
          9     Row 9               
 2147483647     Row 2,147,483,647   

Clearly, the next three inserts would fail, one would succeed, two more would fail, and then they would succeed for the next couple of billion inserts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top