Skip to content

Instantly share code, notes, and snippets.

@pste
Created September 6, 2019 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pste/37b62f89a40d9c2f8eb051c57319b861 to your computer and use it in GitHub Desktop.
Save pste/37b62f89a40d9c2f8eb051c57319b861 to your computer and use it in GitHub Desktop.
Playing with PostgreSQL's sequences
-- lets play with sequences:
create table items (id serial primary key, name varchar(10));
insert into items(name) values ('foo');
-- manually insert into a serial is allowed BUT it breaks the sequence!
insert into items(id,name) values (2,'foo');
-- now what do you expect?
select currval(pg_get_serial_sequence('items', 'id')); -- ouch! nextval is 1!!
-- ok, let's fix it up!
SELECT setval(pg_get_serial_sequence('items', 'id'), (select max(id)+1 from public.items));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment