EN
PostgreSQL - duplicate table with indexes and data
0 points
In this article, we would like to show you how to duplicate table with indexes and data in PostgreSQL.
Quick solution:
xxxxxxxxxx
1
CREATE TABLE "new_table" LIKE "old_table";
2
INSERT INTO "new_table" SELECT * FROM "old_table";
To show how to duplicate table with indexes and data, we will use the following table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will create an exact copy of users
table named users_copy
.
Query:
xxxxxxxxxx
1
CREATE TABLE "users_copy" LIKE "users";
2
INSERT INTO "users_copy" SELECT * FROM "users";
Output:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL,
3
"name" VARCHAR(50) NOT NULL,
4
"surname" VARCHAR(50) NOT NULL,
5
"email" VARCHAR(50),
6
PRIMARY KEY ("id")
7
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "users"
2
( "name", "surname", "email")
3
VALUES
4
('John', 'Stewart', 'john@email.com'),
5
('Chris', 'Brown', 'chris@email.com'),
6
('Kate', 'Lewis', 'kate@email.com'),
7
('Ailisa', 'Gomez', 'ailisa@email.com'),
8
('Gwendolyn', 'James', 'gwen@email.com'),
9
('Simon', 'Collins', 'simon@email.com'),
10
('Taylor', 'Martin', 'taylor@email.com'),
11
('Andrew', 'Thompson', 'andrew@email.com');