Created
February 8, 2016 00:25
-
-
Save gleenn/8239d403a7de230ac371 to your computer and use it in GitHub Desktop.
Doing upsert and adding primary key and fixing sequence on Postgres table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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