Search code examples
postgresqlpsql

Why PSQL meta command cannot be execute at mutliline


Just found out \COPY command can only be execute at one single line, tried this answer's query multiple times. This way seems very unfriendly for writing long queries. And not easy to find out why. I don't think that's a bug, then why.


Solution

  • From here psql and if you are copying out to a file:

    Another way to obtain the same result as \copy ... to is to use the SQL COPY ... TO STDOUT command and terminate it with \g filename or \g |program. Unlike \copy, this method allows the command to span multiple lines; also, variable interpolation and backquote expansion can be used.

    For copying in from a file, borrowing from what pg_dump does:

    CREATE TABLE csv_test (col1 integer, col2 integer);
    
    cat csv_test.csv 
    
    COPY 
      csv_test 
    FROM 
     stdin WITH CSV;
    "19","9"
    "19","5"
    "19","5"
    "19","15"
    "19","5"
    
    \i ~/csv_test.csv 
    COPY 5
    
    select * from csv_test ;
     col1 | col2 
    ------+------
       19 |    9
       19 |    5
       19 |    5
       19 |   15
       19 |    5