How do I copy data from one table to another in postgres using copy command

SqlPostgresqlCopy

Sql Problem Overview


We use copy command to copy data of one table to a file outside database.

Is it possible to copy data of one table to another table using command.

If yes can anyone please share the query.

Or is there any better approach like we can use pg_dump or something like that.

Sql Solutions


Solution 1 - Sql

You cannot easily do that, but there's also no need to do so.

CREATE TABLE mycopy AS
SELECT * FROM mytable;

or

CREATE TABLE mycopy (LIKE mytable INCLUDING ALL);

INSERT INTO mycopy
SELECT * FROM mytable;

If you need to select only some columns or reorder them, you can do this:

INSERT INTO mycopy(colA, colB)
SELECT col1, col2 FROM mytable;

You can also do a selective pg_dump and restore of just the target table.

Solution 2 - Sql

If the columns are the same (names and datatypes) in both tables then you can use the following

INSERT INTO receivingtable (SELECT * FROM sourcetable WHERE column1='parameter' AND column2='anotherparameter');

Solution 3 - Sql

Suppose there is already a table and you want to copy all records from this table to another table which is not currently present in the database then following query will do this task for you:

SELECT * into public."NewTable" FROM public."ExistingTable";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMohitd23View Question on Stackoverflow
Solution 1 - SqlCraig RingerView Answer on Stackoverflow
Solution 2 - SqlSteve IrwinView Answer on Stackoverflow
Solution 3 - SqlManish JainView Answer on Stackoverflow