Search code examples
sqlpostgresqllimitdumppostgresql-copy

COPY command postgres syntax error


I am trying to export from a large postgres 8.1 table a couple of rows using

copy (select * from tablename limit 100) to 'absolute path to file';

but I get

ERROR:  syntax error at or near "(" at character 6.

Any ideas what might be going wrong ? By the way I am not super user in the database but I believe that would have produced a different kind of error. If you have any other idea to dump a couple of rows from SQL (in a format to insert them easily, without coding) other than using copy I open to suggestions.


Solution

  • To overcome the shortcoming of version 8.1 you can create a TEMPORARY TABLE and use it in COPY TO:

    CREATE TEMP TABLE t_tmp AS
    SELECT * FROM tablename LIMIT 100;
    
    COPY t_tmp TO '/absolute/path/to/file';
    

    Temp. tables are dropped at the end of a session automatically. If you want to keep the connection open you could drop the table explicitly or wrap it in a transaction which you roll back (what's already written to the file is never rolled back.)

    BEGIN;
    CREATE ...;
    COPY ...;
    ROLLBACK;
    

    Or you upgrade to a more recent version, which would be a very good idea in general.
    PostgreSQL 8.1 has reached end of life in Nov. 2010.