3

So I'm uploading some 150,000 rows of data into a database over HTTP via Python backend, and the upload takes a while, thus I'm inserting it into a new table which I then swap with (by renaming) the old table:

create table tmp (like main);
alter sequence main_id_seq restart;
alter table tmp alter column id set default nextval('main_id_seq');
drop table main cascade;  -- THIS REMOVES THE SEQUENCE ^^^^^^^
alter table tmp rename to main;

How can I alter the sequence to not be linked to the main table, so that when I drop the main table, the sequence would stay linked to the current tmp table (new main)?

0

2 Answers 2

3

You can do that by making the column "owning" the sequence

alter sequence main_id_seq
  owned by main.id;
Sign up to request clarification or add additional context in comments.

3 Comments

Figured there must be a simple way like this, but couldn't find the owned by from anywhere... Thanks!
Yeah I gotta read the docs more, I'm still rather new with PSQL. Will make some further research next time, thanks :)
1

use alter sequence:

t=# create table s120(i bigserial);
CREATE TABLE
t=# \d+ s120;
                                            Table "public.s120"
 Column |  Type  |                    Modifiers                     | Storage | Stats target | Description
--------+--------+--------------------------------------------------+---------+--------------+-------------
 i      | bigint | not null default nextval('s120_i_seq'::regclass) | plain   |              |

t=# create table s121(i bigint);
CREATE TABLE
t=# alter sequence s120_i_seq owned by s121.i;
ALTER SEQUENCE
t=# drop table s120;
DROP TABLE
t=# alter table s121 alter COLUMN i set default nextval('s120_i_seq'::regclass);
ALTER TABLE
t=# \d+ s121
                                       Table "public.s121"
 Column |  Type  |                Modifiers                | Storage | Stats target | Description
--------+--------+-----------------------------------------+---------+--------------+-------------
 i      | bigint | default nextval('s120_i_seq'::regclass) | plain   |              |

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.