Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: starting a sequence at MAX(the_column)+1

I want to add a sequence to a column that might already have data, so I'm trying to start it beyond whatever's already there. Assuming there already is data, I would like to have done it this way:

CREATE SEQUENCE my_sequence MINVALUE 1000000 START
    (SELECT MAX(id_column) FROM my_table) OWNED BY my_table.id_column;

but it keeps dying at ( claiming syntax error. It's like the start value has to be cold hard numbers--nothing symbolic.

Of course, an even better solution would be if the sequence could be intelligent enough to avoid duplicate values, since id_column has a unique constraint on it--that's why I'm doing this. But from what I can tell, that's not possible.

I also tried skipping the START and then doing:

ALTER SEQUENCE my_sequence RESTART WITH (SELECT max(id_column)+1 FROM my_table);

but, again, it doesn't seem like to symbolic start values.

I'm running PostgreSQL 9.4 but some of our customers are using stuff as primitive as 8.3.

like image 911
Opux Avatar asked May 05 '16 18:05

Opux


People also ask

What happens when sequence reaches max value Postgres?

If the limit is reached, the next number generated will be the minvalue or maxvalue , respectively. If NO CYCLE is specified, any calls to nextval after the sequence has reached its maximum value will return an error.

What is sequence default start with value?

The default starting value is minvalue for ascending sequences and maxvalue for descending ones.

How do I change the sequence number in PostgreSQL?

ALTER SEQUENCE changes the parameters of an existing sequence generator. Any parameters not specifically set in the ALTER SEQUENCE command retain their prior settings. You must own the sequence to use ALTER SEQUENCE . To change a sequence's schema, you must also have CREATE privilege on the new schema.


2 Answers

You can't specify a dynamic value for the start value.

But you can set the value once the sequence is created:

CREATE SEQUENCE my_sequence MINVALUE 1000000 OWNED BY my_table.id_column;
select setval('my_sequence',  (SELECT MAX(id_column) FROM my_table));
like image 88
a_horse_with_no_name Avatar answered Oct 13 '22 02:10

a_horse_with_no_name


You can restore you sequence by request:

select setval('my_sequence', (SELECT MAX(id_column) FROM my_table));

Applicable for Postgres 9.2.

like image 40
Secrius Avatar answered Oct 13 '22 00:10

Secrius