Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gleenn/8239d403a7de230ac371 to your computer and use it in GitHub Desktop.
Save gleenn/8239d403a7de230ac371 to your computer and use it in GitHub Desktop.
Doing upsert and adding primary key and fixing sequence on Postgres table
create table foo(id int, text text);
create unique index foo_id_pkey on foo(id);
create sequence foo_id_seq;
delete from foo where id is null;
alter table foo add primary key using index foo_id_pkey;
alter table foo alter id set default nextval('foo_id_seq');
;; to hack around potentially already used sequence values
select nextval('foo_id_seq');
update foo set id = id - <num skipped ids> where id >= <value of id after gap>;
insert into foo(text) values ('blah blah'); => INSERT 0 1 ;; yayaya
;; and the real money
insert into foo(id, text) values(1, 'foobar') on conflict (id) do update set text = 'something else';
;; row with id = 1 now has text = 'something else'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment