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

后端 未结 4 1408
我在风中等你
我在风中等你 2021-02-04 17:52

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

4条回答
  •  萌比男神i
    2021-02-04 18:05

    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
    

提交回复
热议问题