Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to copy a subset of a table's rows from one database to another in Postgres?

Tags:

sql

postgresql

I've got a production DB with, say, ten million rows. I'd like to extract the 10,000 or so rows from the past hour off of production and copy them to my local box. How do I do that?

Let's say the query is:

SELECT * FROM mytable WHERE date > '2009-01-05 12:00:00';

How do I take the output, export it to some sort of dump file, and then import that dump file into my local development copy of the database -- as quickly and easily as possible?

like image 239
mike Avatar asked Jan 05 '09 23:01

mike


People also ask

How do I copy a row from one database to another?

A simple way is to open SSMS and Right click on database and go to Tasks > Import Data and follow the wizard to set source and destination. This way if data exists on different systems and even if you wish to change structure you can do. Also append, or cleanout data at same time from destination. Save this answer.

How do I copy a table data from one table to another 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.

How do I copy a table from one database to another in DBMS?

If you want to copy the data of one SQL table into another SQL table in the same SQL server, then it is possible by using the SELECT INTO statement in SQL. The SELECT INTO statement in Structured Query Language copies the content from one existing table into the new table.


2 Answers

Source:

psql -c "COPY (SELECT * FROM mytable WHERE ...) TO STDOUT" > mytable.copy

Destination:

psql -c "COPY mytable FROM STDIN" < mytable.copy

This assumes mytable has the same schema and column order in both the source and destination. If this isn't the case, you could try STDOUT CSV HEADER and STDIN CSV HEADER instead of STDOUT and STDIN, but I haven't tried it.

If you have any custom triggers on mytable, you may need to disable them on import:

psql -c "ALTER TABLE mytable DISABLE TRIGGER USER; \
         COPY mytable FROM STDIN; \
         ALTER TABLE mytable ENABLE TRIGGER USER" < mytable.copy
like image 93
Joey Adams Avatar answered Nov 08 '22 18:11

Joey Adams


source server:

BEGIN;

CREATE TEMP TABLE mmm_your_table_here AS
    SELECT * FROM your_table_here WHERE your_condition_here;

COPY mmm_your_table_here TO 'u:\\source.copy';

ROLLBACK;

your local box:

-- your_destination_table_here must be created first on your box

COPY your_destination_table_here FROM 'u:\\source.copy';

article: http://www.postgresql.org/docs/8.1/static/sql-copy.html

like image 31
Michael Buen Avatar answered Nov 08 '22 18:11

Michael Buen