Export specific rows from a PostgreSQL table as INSERT SQL script

后端 未结 9 764
野趣味
野趣味 2020-11-30 17:01

I have a database schema named: nyummy and a table named cimory:

create table nyummy.cimory (
  id numeric(10,0) not null,
  name c         


        
9条回答
  •  没有蜡笔的小新
    2020-11-30 17:15

    For a data-only export use COPY.
    You get a file with one table row per line as plain text (not INSERT commands), it's smaller and faster:

    COPY (SELECT * FROM nyummy.cimory WHERE city = 'tokio') TO '/path/to/file.csv';
    

    Import the same to another table of the same structure anywhere with:

    COPY other_tbl FROM '/path/to/file.csv';
    

    COPY writes and read files local to the server, unlike client programs like pg_dump or psql which read and write files local to the client. If both run on the same machine, it doesn't matter much, but it does for remote connections.

    There is also the \copy command of psql that:

    Performs a frontend (client) copy. This is an operation that runs an SQL COPY command, but instead of the server reading or writing the specified file, psql reads or writes the file and routes the data between the server and the local file system. This means that file accessibility and privileges are those of the local user, not the server, and no SQL superuser privileges are required.

提交回复
热议问题