Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Postgres table while maintaining primary key autoincrement

Tags:

postgresql

I am trying to copy a table with this postgres command however the primary key autoincrement feature does not copy over. Is there any quick and simple way to accomplish this? Thanks!

CREATE TABLE table2 AS TABLE table;
like image 709
sheldonk Avatar asked Mar 06 '13 03:03

sheldonk


People also ask

How do I duplicate a table in PostgreSQL?

To copy a table with partial data from an existing table, users can use the following statement: Syntax: CREATE TABLE new_table AS SELECT * FROM existing_table WHERE condition; The condition in the WHERE clause of the query defines which rows of the existing table will be copied to the new table.

Is primary key auto increment by default in PostgreSQL?

By simply setting our id column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our id column with a unique, primary key value for every INSERT .

Does PostgreSQL have auto increment?

In PostgreSQL, a sequence is a special kind of database object that generates a sequence of integers. A sequence is often used as the primary key column in a table. The SERIAL pseudo-type can be used to generate a sequence while creating a new table.


1 Answers

Here's what I'd do:

BEGIN;
LOCK TABLE oldtable; 
CREATE TABLE newtable (LIKE oldtable INCLUDING ALL);
INSERT INTO newtable SELECT * FROM oldtable;
SELECT setval('the_seq_name', (SELECT max(id) FROM oldtable)+1);
COMMIT;

... though this is a moderately unusual thing to need to do and I'd be interested in what problem you're trying to solve.

like image 128
Craig Ringer Avatar answered Sep 21 '22 18:09

Craig Ringer