Languages
[Edit]
EN

PostgreSQL - duplicate table

0 points
Created by:
Dirask JS Member
3460

In this article, we would like to show you how to duplicate table in PostgreSQL.

Quick solution:

CREATE TABLE "new_table" AS SELECT * FROM "old_table";

Note:

This will copy only the data from old_table. If you want to copy the indexes too go to this article: PostgreSQL - duplicate table with indexes and data.

Practical example

To show how to duplicate table, we will use the following table:

PostgreSQL - example data used to duplicate table
PostgreSQL - example data used to duplicate table

Note:

At the end of this article you can find database preparation SQL queries.

Example

In this example, we will create a copy of users table named users_copy.

Query:

CREATE TABLE "users_copy" AS SELECT * FROM "users";

Output:

PostgreSQL - duplicate table - result in HeidiSQL
PostgreSQL - duplicate table - result in HeidiSQL

Database preparation

create_tables.sql file:

CREATE TABLE "users" (
	"id" SERIAL,
	"name" VARCHAR(50) NOT NULL,
	"surname" VARCHAR(50) NOT NULL,
	"email" VARCHAR(50),
	PRIMARY KEY ("id")
);

insert_data.sql file:

INSERT INTO "users"
	( "name", "surname", "email")
VALUES
	('John', 'Stewart', 'john@email.com'),
	('Chris', 'Brown', 'chris@email.com'),
	('Kate', 'Lewis', 'kate@email.com'),
	('Ailisa', 'Gomez', 'ailisa@email.com'),
	('Gwendolyn', 'James', 'gwen@email.com'),
	('Simon', 'Collins', 'simon@email.com'),
	('Taylor', 'Martin', 'taylor@email.com'),
	('Andrew', 'Thompson', 'andrew@email.com');

Related posts

PostgreSQL - problems

PostgreSQL - duplicate table
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join