{
    "mode": "man",
    "parameter": "COPY",
    "section": "7",
    "url": "https://www.chedong.com/phpMan.php/man/COPY/7/json",
    "generated": "2026-06-03T01:28:51Z",
    "synopsis": "COPY tablename [ ( columnname [, ...] ) ]\nFROM { 'filename' | PROGRAM 'command' | STDIN }\n[ [ WITH ] ( option [, ...] ) ]\n[ WHERE condition ]\nCOPY { tablename [ ( columnname [, ...] ) ] | ( query ) }\nTO { 'filename' | PROGRAM 'command' | STDOUT }\n[ [ WITH ] ( option [, ...] ) ]\nwhere option can be one of:\nFORMAT formatname\nFREEZE [ boolean ]\nDELIMITER 'delimitercharacter'\nNULL 'nullstring'\nHEADER [ boolean ]\nQUOTE 'quotecharacter'\nESCAPE 'escapecharacter'\nFORCEQUOTE { ( columnname [, ...] ) | * }\nFORCENOTNULL ( columnname [, ...] )\nFORCENULL ( columnname [, ...] )\nENCODING 'encodingname'",
    "sections": {
        "NAME": {
            "content": "COPY - copy data between a file and a table\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "COPY tablename [ ( columnname [, ...] ) ]\nFROM { 'filename' | PROGRAM 'command' | STDIN }\n[ [ WITH ] ( option [, ...] ) ]\n[ WHERE condition ]\n\nCOPY { tablename [ ( columnname [, ...] ) ] | ( query ) }\nTO { 'filename' | PROGRAM 'command' | STDOUT }\n[ [ WITH ] ( option [, ...] ) ]\n\nwhere option can be one of:\n\nFORMAT formatname\nFREEZE [ boolean ]\nDELIMITER 'delimitercharacter'\nNULL 'nullstring'\nHEADER [ boolean ]\nQUOTE 'quotecharacter'\nESCAPE 'escapecharacter'\nFORCEQUOTE { ( columnname [, ...] ) | * }\nFORCENOTNULL ( columnname [, ...] )\nFORCENULL ( columnname [, ...] )\nENCODING 'encodingname'\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "COPY moves data between PostgreSQL tables and standard file-system files.  COPY TO copies the\ncontents of a table to a file, while COPY FROM copies data from a file to a table (appending\nthe data to whatever is in the table already).  COPY TO can also copy the results of a SELECT\nquery.\n\nIf a column list is specified, COPY TO copies only the data in the specified columns to the\nfile. For COPY FROM, each field in the file is inserted, in order, into the specified column.\nTable columns not specified in the COPY FROM column list will receive their default values.\n\nCOPY with a file name instructs the PostgreSQL server to directly read from or write to a\nfile. The file must be accessible by the PostgreSQL user (the user ID the server runs as) and\nthe name must be specified from the viewpoint of the server. When PROGRAM is specified, the\nserver executes the given command and reads from the standard output of the program, or\nwrites to the standard input of the program. The command must be specified from the viewpoint\nof the server, and be executable by the PostgreSQL user. When STDIN or STDOUT is specified,\ndata is transmitted via the connection between the client and the server.\n\nEach backend running COPY will report its progress in the pgstatprogresscopy view. See\nSection 28.4.6 for details.\n",
            "subsections": []
        },
        "PARAMETERS": {
            "content": "tablename\nThe name (optionally schema-qualified) of an existing table.\n\ncolumnname\nAn optional list of columns to be copied. If no column list is specified, all columns of\nthe table except generated columns will be copied.\n\nquery\nA SELECT, VALUES, INSERT, UPDATE, or DELETE command whose results are to be copied. Note\nthat parentheses are required around the query.\n\nFor INSERT, UPDATE and DELETE queries a RETURNING clause must be provided, and the target\nrelation must not have a conditional rule, nor an ALSO rule, nor an INSTEAD rule that\nexpands to multiple statements.\n\nfilename\nThe path name of the input or output file. An input file name can be an absolute or\nrelative path, but an output file name must be an absolute path. Windows users might need\nto use an E'' string and double any backslashes used in the path name.\n\nPROGRAM\nA command to execute. In COPY FROM, the input is read from standard output of the\ncommand, and in COPY TO, the output is written to the standard input of the command.\n\nNote that the command is invoked by the shell, so if you need to pass any arguments to\nshell command that come from an untrusted source, you must be careful to strip or escape\nany special characters that might have a special meaning for the shell. For security\nreasons, it is best to use a fixed command string, or at least avoid passing any user\ninput in it.\n\nSTDIN\nSpecifies that input comes from the client application.\n\nSTDOUT\nSpecifies that output goes to the client application.\n\nboolean\nSpecifies whether the selected option should be turned on or off. You can write TRUE, ON,\nor 1 to enable the option, and FALSE, OFF, or 0 to disable it. The boolean value can also\nbe omitted, in which case TRUE is assumed.\n\nFORMAT\nSelects the data format to be read or written: text, csv (Comma Separated Values), or\nbinary. The default is text.\n\nFREEZE\nRequests copying the data with rows already frozen, just as they would be after running\nthe VACUUM FREEZE command. This is intended as a performance option for initial data\nloading. Rows will be frozen only if the table being loaded has been created or truncated\nin the current subtransaction, there are no cursors open and there are no older snapshots\nheld by this transaction. It is currently not possible to perform a COPY FREEZE on a\npartitioned table.\n\nNote that all other sessions will immediately be able to see the data once it has been\nsuccessfully loaded. This violates the normal rules of MVCC visibility and users\nspecifying should be aware of the potential problems this might cause.\n\nDELIMITER\nSpecifies the character that separates columns within each row (line) of the file. The\ndefault is a tab character in text format, a comma in CSV format. This must be a single\none-byte character. This option is not allowed when using binary format.\n\nNULL\nSpecifies the string that represents a null value. The default is \\N (backslash-N) in\ntext format, and an unquoted empty string in CSV format. You might prefer an empty string\neven in text format for cases where you don't want to distinguish nulls from empty\nstrings. This option is not allowed when using binary format.\n\nNote\nWhen using COPY FROM, any data item that matches this string will be stored as a null\nvalue, so you should make sure that you use the same string as you used with COPY TO.\n\nHEADER\nSpecifies that the file contains a header line with the names of each column in the file.\nOn output, the first line contains the column names from the table, and on input, the\nfirst line is ignored. This option is allowed only when using CSV format.\n\nQUOTE\nSpecifies the quoting character to be used when a data value is quoted. The default is\ndouble-quote. This must be a single one-byte character. This option is allowed only when\nusing CSV format.\n\nESCAPE\nSpecifies the character that should appear before a data character that matches the QUOTE\nvalue. The default is the same as the QUOTE value (so that the quoting character is\ndoubled if it appears in the data). This must be a single one-byte character. This option\nis allowed only when using CSV format.\n\nFORCEQUOTE\nForces quoting to be used for all non-NULL values in each specified column.  NULL output\nis never quoted. If * is specified, non-NULL values will be quoted in all columns. This\noption is allowed only in COPY TO, and only when using CSV format.\n\nFORCENOTNULL\nDo not match the specified columns' values against the null string. In the default case\nwhere the null string is empty, this means that empty values will be read as zero-length\nstrings rather than nulls, even when they are not quoted. This option is allowed only in\nCOPY FROM, and only when using CSV format.\n\nFORCENULL\nMatch the specified columns' values against the null string, even if it has been quoted,\nand if a match is found set the value to NULL. In the default case where the null string\nis empty, this converts a quoted empty string into NULL. This option is allowed only in\nCOPY FROM, and only when using CSV format.\n\nENCODING\nSpecifies that the file is encoded in the encodingname. If this option is omitted, the\ncurrent client encoding is used. See the Notes below for more details.\n\nWHERE\nThe optional WHERE clause has the general form\n\nWHERE condition\n\nwhere condition is any expression that evaluates to a result of type boolean. Any row\nthat does not satisfy this condition will not be inserted to the table. A row satisfies\nthe condition if it returns true when the actual row values are substituted for any\nvariable references.\n\nCurrently, subqueries are not allowed in WHERE expressions, and the evaluation does not\nsee any changes made by the COPY itself (this matters when the expression contains calls\nto VOLATILE functions).\n",
            "subsections": []
        },
        "OUTPUTS": {
            "content": "On successful completion, a COPY command returns a command tag of the form\n\nCOPY count\n\nThe count is the number of rows copied.\n\nNote\npsql will print this command tag only if the command was not COPY ... TO STDOUT, or the\nequivalent psql meta-command \\copy ... to stdout. This is to prevent confusing the\ncommand tag with the data that was just printed.\n",
            "subsections": []
        },
        "NOTES": {
            "content": "COPY TO can be used only with plain tables, not views, and does not copy rows from child\ntables or child partitions. For example, COPY table TO copies the same rows as SELECT * FROM\nONLY table. The syntax COPY (SELECT * FROM table) TO ...  can be used to dump all of the rows\nin an inheritance hierarchy, partitioned table, or view.\n\nCOPY FROM can be used with plain, foreign, or partitioned tables or with views that have\nINSTEAD OF INSERT triggers.\n\nYou must have select privilege on the table whose values are read by COPY TO, and insert\nprivilege on the table into which values are inserted by COPY FROM. It is sufficient to have\ncolumn privileges on the column(s) listed in the command.\n\nIf row-level security is enabled for the table, the relevant SELECT policies will apply to\nCOPY table TO statements. Currently, COPY FROM is not supported for tables with row-level\nsecurity. Use equivalent INSERT statements instead.\n\nFiles named in a COPY command are read or written directly by the server, not by the client\napplication. Therefore, they must reside on or be accessible to the database server machine,\nnot the client. They must be accessible to and readable or writable by the PostgreSQL user\n(the user ID the server runs as), not the client. Similarly, the command specified with\nPROGRAM is executed directly by the server, not by the client application, must be executable\nby the PostgreSQL user.  COPY naming a file or command is only allowed to database superusers\nor users who are granted one of the roles pgreadserverfiles, pgwriteserverfiles, or\npgexecuteserverprogram, since it allows reading or writing any file or running a program\nthat the server has privileges to access.\n\nDo not confuse COPY with the psql instruction \\copy.  \\copy invokes COPY FROM STDIN or COPY\nTO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus,\nfile accessibility and access rights depend on the client rather than the server when \\copy\nis used.\n\nIt is recommended that the file name used in COPY always be specified as an absolute path.\nThis is enforced by the server in the case of COPY TO, but for COPY FROM you do have the\noption of reading from a file specified by a relative path. The path will be interpreted\nrelative to the working directory of the server process (normally the cluster's data\ndirectory), not the client's working directory.\n\nExecuting a command with PROGRAM might be restricted by the operating system's access control\nmechanisms, such as SELinux.\n\nCOPY FROM will invoke any triggers and check constraints on the destination table. However,\nit will not invoke rules.\n\nFor identity columns, the COPY FROM command will always write the column values provided in\nthe input data, like the INSERT option OVERRIDING SYSTEM VALUE.\n\nCOPY input and output is affected by DateStyle. To ensure portability to other PostgreSQL\ninstallations that might use non-default DateStyle settings, DateStyle should be set to ISO\nbefore using COPY TO. It is also a good idea to avoid dumping data with IntervalStyle set to\nsqlstandard, because negative interval values might be misinterpreted by a server that has a\ndifferent setting for IntervalStyle.\n\nInput data is interpreted according to ENCODING option or the current client encoding, and\noutput data is encoded in ENCODING or the current client encoding, even if the data does not\npass through the client but is read from or written to a file directly by the server.\n\nCOPY stops operation at the first error. This should not lead to problems in the event of a\nCOPY TO, but the target table will already have received earlier rows in a COPY FROM. These\nrows will not be visible or accessible, but they still occupy disk space. This might amount\nto a considerable amount of wasted disk space if the failure happened well into a large copy\noperation. You might wish to invoke VACUUM to recover the wasted space.\n\nFORCENULL and FORCENOTNULL can be used simultaneously on the same column. This results in\nconverting quoted null strings to null values and unquoted null strings to empty strings.\n",
            "subsections": []
        },
        "FILE FORMATS": {
            "content": "",
            "subsections": [
                {
                    "name": "Text Format",
                    "content": "When the text format is used, the data read or written is a text file with one line per table\nrow. Columns in a row are separated by the delimiter character. The column values themselves\nare strings generated by the output function, or acceptable to the input function, of each\nattribute's data type. The specified null string is used in place of columns that are null.\nCOPY FROM will raise an error if any line of the input file contains more or fewer columns\nthan are expected.\n\nEnd of data can be represented by a single line containing just backslash-period (\\.). An\nend-of-data marker is not necessary when reading from a file, since the end of file serves\nperfectly well; it is needed only when copying data to or from client applications using\npre-3.0 client protocol.\n\nBackslash characters (\\) can be used in the COPY data to quote data characters that might\notherwise be taken as row or column delimiters. In particular, the following characters must\nbe preceded by a backslash if they appear as part of a column value: backslash itself,\nnewline, carriage return, and the current delimiter character.\n\nThe specified null string is sent by COPY TO without adding any backslashes; conversely, COPY\nFROM matches the input against the null string before removing backslashes. Therefore, a null\nstring such as \\N cannot be confused with the actual data value \\N (which would be\nrepresented as \\\\N).\n\nThe following special backslash sequences are recognized by COPY FROM:\n\n┌─────────┬───────────────────────────────────┐\n│Sequence │ Represents                        │\n├─────────┼───────────────────────────────────┤\n│\\b       │ Backspace (ASCII 8)               │\n├─────────┼───────────────────────────────────┤\n│\\f       │ Form feed (ASCII 12)              │\n├─────────┼───────────────────────────────────┤\n│\\n       │ Newline (ASCII 10)                │\n├─────────┼───────────────────────────────────┤\n│\\r       │ Carriage return (ASCII 13)        │\n├─────────┼───────────────────────────────────┤\n│\\t       │ Tab (ASCII 9)                     │\n├─────────┼───────────────────────────────────┤\n│\\v       │ Vertical tab (ASCII 11)           │\n├─────────┼───────────────────────────────────┤\n│\\digits  │ Backslash followed by one to      │\n│         │ three octal digits specifies      │\n│         │        the byte with that numeric │\n│         │ code                              │\n├─────────┼───────────────────────────────────┤\n│\\xdigits │ Backslash x followed by one or    │\n│         │ two hex digits specifies          │\n│         │        the byte with that numeric │\n│         │ code                              │\n└─────────┴───────────────────────────────────┘\nPresently, COPY TO will never emit an octal or hex-digits backslash sequence, but it does use\nthe other sequences listed above for those control characters.\n\nAny other backslashed character that is not mentioned in the above table will be taken to\nrepresent itself. However, beware of adding backslashes unnecessarily, since that might\naccidentally produce a string matching the end-of-data marker (\\.) or the null string (\\N by\ndefault). These strings will be recognized before any other backslash processing is done.\n\nIt is strongly recommended that applications generating COPY data convert data newlines and\ncarriage returns to the \\n and \\r sequences respectively. At present it is possible to\nrepresent a data carriage return by a backslash and carriage return, and to represent a data\nnewline by a backslash and newline. However, these representations might not be accepted in\nfuture releases. They are also highly vulnerable to corruption if the COPY file is\ntransferred across different machines (for example, from Unix to Windows or vice versa).\n\nAll backslash sequences are interpreted after encoding conversion. The bytes specified with\nthe octal and hex-digit backslash sequences must form valid characters in the database\nencoding.\n\nCOPY TO will terminate each row with a Unix-style newline (“\\n”). Servers running on\nMicrosoft Windows instead output carriage return/newline (“\\r\\n”), but only for COPY to a\nserver file; for consistency across platforms, COPY TO STDOUT always sends “\\n” regardless of\nserver platform.  COPY FROM can handle lines ending with newlines, carriage returns, or\ncarriage return/newlines. To reduce the risk of error due to un-backslashed newlines or\ncarriage returns that were meant as data, COPY FROM will complain if the line endings in the\ninput are not all alike.\n"
                },
                {
                    "name": "CSV Format",
                    "content": "This format option is used for importing and exporting the Comma Separated Value (CSV) file\nformat used by many other programs, such as spreadsheets. Instead of the escaping rules used\nby PostgreSQL's standard text format, it produces and recognizes the common CSV escaping\nmechanism.\n\nThe values in each record are separated by the DELIMITER character. If the value contains the\ndelimiter character, the QUOTE character, the NULL string, a carriage return, or line feed\ncharacter, then the whole value is prefixed and suffixed by the QUOTE character, and any\noccurrence within the value of a QUOTE character or the ESCAPE character is preceded by the\nescape character. You can also use FORCEQUOTE to force quotes when outputting non-NULL\nvalues in specific columns.\n\nThe CSV format has no standard way to distinguish a NULL value from an empty string.\nPostgreSQL's COPY handles this by quoting. A NULL is output as the NULL parameter string and\nis not quoted, while a non-NULL value matching the NULL parameter string is quoted. For\nexample, with the default settings, a NULL is written as an unquoted empty string, while an\nempty string data value is written with double quotes (\"\"). Reading values follows similar\nrules. You can use FORCENOTNULL to prevent NULL input comparisons for specific columns. You\ncan also use FORCENULL to convert quoted null string data values to NULL.\n\nBecause backslash is not a special character in the CSV format, \\., the end-of-data marker,\ncould also appear as a data value. To avoid any misinterpretation, a \\.  data value appearing\nas a lone entry on a line is automatically quoted on output, and on input, if quoted, is not\ninterpreted as the end-of-data marker. If you are loading a file created by another\napplication that has a single unquoted column and might have a value of \\., you might need to\nquote that value in the input file.\n\nNote\nIn CSV format, all characters are significant. A quoted value surrounded by white space,\nor any characters other than DELIMITER, will include those characters. This can cause\nerrors if you import data from a system that pads CSV lines with white space out to some\nfixed width. If such a situation arises you might need to preprocess the CSV file to\nremove the trailing white space, before importing the data into PostgreSQL.\n\nNote\nCSV format will both recognize and produce CSV files with quoted values containing\nembedded carriage returns and line feeds. Thus the files are not strictly one line per\ntable row like text-format files.\n\nNote\nMany programs produce strange and occasionally perverse CSV files, so the file format is\nmore a convention than a standard. Thus you might encounter some files that cannot be\nimported using this mechanism, and COPY might produce files that other programs cannot\nprocess.\n"
                },
                {
                    "name": "Binary Format",
                    "content": "The binary format option causes all data to be stored/read as binary format rather than as\ntext. It is somewhat faster than the text and CSV formats, but a binary-format file is less\nportable across machine architectures and PostgreSQL versions. Also, the binary format is\nvery data type specific; for example it will not work to output binary data from a smallint\ncolumn and read it into an integer column, even though that would work fine in text format.\n\nThe binary file format consists of a file header, zero or more tuples containing the row\ndata, and a file trailer. Headers and data are in network byte order.\n\nNote\nPostgreSQL releases before 7.4 used a different binary file format.\n"
                },
                {
                    "name": "File Header",
                    "content": "The file header consists of 15 bytes of fixed fields, followed by a variable-length\nheader extension area. The fixed fields are:\n\nSignature\n11-byte sequence PGCOPY\\n\\377\\r\\n\\0 — note that the zero byte is a required part of\nthe signature. (The signature is designed to allow easy identification of files that\nhave been munged by a non-8-bit-clean transfer. This signature will be changed by\nend-of-line-translation filters, dropped zero bytes, dropped high bits, or parity\nchanges.)\n\nFlags field\n32-bit integer bit mask to denote important aspects of the file format. Bits are\nnumbered from 0 (LSB) to 31 (MSB). Note that this field is stored in network byte\norder (most significant byte first), as are all the integer fields used in the file\nformat. Bits 16–31 are reserved to denote critical file format issues; a reader\nshould abort if it finds an unexpected bit set in this range. Bits 0–15 are reserved\nto signal backwards-compatible format issues; a reader should simply ignore any\nunexpected bits set in this range. Currently only one flag bit is defined, and the\nrest must be zero:\n\nBit 16\nIf 1, OIDs are included in the data; if 0, not. Oid system columns are not\nsupported in PostgreSQL anymore, but the format still contains the indicator.\n\nHeader extension area length\n32-bit integer, length in bytes of remainder of header, not including self.\nCurrently, this is zero, and the first tuple follows immediately. Future changes to\nthe format might allow additional data to be present in the header. A reader should\nsilently skip over any header extension data it does not know what to do with.\n\nThe header extension area is envisioned to contain a sequence of self-identifying chunks.\nThe flags field is not intended to tell readers what is in the extension area. Specific\ndesign of header extension contents is left for a later release.\n\nThis design allows for both backwards-compatible header additions (add header extension\nchunks, or set low-order flag bits) and non-backwards-compatible changes (set high-order\nflag bits to signal such changes, and add supporting data to the extension area if\nneeded).\n"
                },
                {
                    "name": "Tuples",
                    "content": "Each tuple begins with a 16-bit integer count of the number of fields in the tuple.\n(Presently, all tuples in a table will have the same count, but that might not always be\ntrue.) Then, repeated for each field in the tuple, there is a 32-bit length word followed\nby that many bytes of field data. (The length word does not include itself, and can be\nzero.) As a special case, -1 indicates a NULL field value. No value bytes follow in the\nNULL case.\n\nThere is no alignment padding or any other extra data between fields.\n\nPresently, all data values in a binary-format file are assumed to be in binary format\n(format code one). It is anticipated that a future extension might add a header field\nthat allows per-column format codes to be specified.\n\nTo determine the appropriate binary format for the actual tuple data you should consult\nthe PostgreSQL source, in particular the *send and *recv functions for each column's data\ntype (typically these functions are found in the src/backend/utils/adt/ directory of the\nsource distribution).\n\nIf OIDs are included in the file, the OID field immediately follows the field-count word.\nIt is a normal field except that it's not included in the field-count. Note that oid\nsystem columns are not supported in current versions of PostgreSQL.\n"
                },
                {
                    "name": "File Trailer",
                    "content": "The file trailer consists of a 16-bit integer word containing -1. This is easily\ndistinguished from a tuple's field-count word.\n\nA reader should report an error if a field-count word is neither -1 nor the expected\nnumber of columns. This provides an extra check against somehow getting out of sync with\nthe data.\n"
                }
            ]
        },
        "EXAMPLES": {
            "content": "The following example copies a table to the client using the vertical bar (|) as the field\ndelimiter:\n\nCOPY country TO STDOUT (DELIMITER '|');\n\nTo copy data from a file into the country table:\n\nCOPY country FROM '/usr1/proj/bray/sql/countrydata';\n\nTo copy into a file just the countries whose names start with 'A':\n\nCOPY (SELECT * FROM country WHERE countryname LIKE 'A%') TO '/usr1/proj/bray/sql/alistcountries.copy';\n\nTo copy into a compressed file, you can pipe the output through an external compression\nprogram:\n\nCOPY country TO PROGRAM 'gzip > /usr1/proj/bray/sql/countrydata.gz';\n\nHere is a sample of data suitable for copying into a table from STDIN:\n\nAF      AFGHANISTAN\nAL      ALBANIA\nDZ      ALGERIA\nZM      ZAMBIA\nZW      ZIMBABWE\n\nNote that the white space on each line is actually a tab character.\n\nThe following is the same data, output in binary format. The data is shown after filtering\nthrough the Unix utility od -c. The table has three columns; the first has type char(2), the\nsecond has type text, and the third has type integer. All the rows have a null value in the\nthird column.\n\n0000000   P   G   C   O   P   Y  \\n 377  \\r  \\n  \\0  \\0  \\0  \\0  \\0  \\0\n0000020  \\0  \\0  \\0  \\0 003  \\0  \\0  \\0 002   A   F  \\0  \\0  \\0 013   A\n0000040   F   G   H   A   N   I   S   T   A   N 377 377 377 377  \\0 003\n0000060  \\0  \\0  \\0 002   A   L  \\0  \\0  \\0 007   A   L   B   A   N   I\n0000100   A 377 377 377 377  \\0 003  \\0  \\0  \\0 002   D   Z  \\0  \\0  \\0\n0000120 007   A   L   G   E   R   I   A 377 377 377 377  \\0 003  \\0  \\0\n0000140  \\0 002   Z   M  \\0  \\0  \\0 006   Z   A   M   B   I   A 377 377\n0000160 377 377  \\0 003  \\0  \\0  \\0 002   Z   W  \\0  \\0  \\0  \\b   Z   I\n0000200   M   B   A   B   W   E 377 377 377 377 377 377\n",
            "subsections": []
        },
        "COMPATIBILITY": {
            "content": "There is no COPY statement in the SQL standard.\n\nThe following syntax was used before PostgreSQL version 9.0 and is still supported:\n\nCOPY tablename [ ( columnname [, ...] ) ]\nFROM { 'filename' | STDIN }\n[ [ WITH ]\n[ BINARY ]\n[ DELIMITER [ AS ] 'delimitercharacter' ]\n[ NULL [ AS ] 'nullstring' ]\n[ CSV [ HEADER ]\n[ QUOTE [ AS ] 'quotecharacter' ]\n[ ESCAPE [ AS ] 'escapecharacter' ]\n[ FORCE NOT NULL columnname [, ...] ] ] ]\n\nCOPY { tablename [ ( columnname [, ...] ) ] | ( query ) }\nTO { 'filename' | STDOUT }\n[ [ WITH ]\n[ BINARY ]\n[ DELIMITER [ AS ] 'delimitercharacter' ]\n[ NULL [ AS ] 'nullstring' ]\n[ CSV [ HEADER ]\n[ QUOTE [ AS ] 'quotecharacter' ]\n[ ESCAPE [ AS ] 'escapecharacter' ]\n[ FORCE QUOTE { columnname [, ...] | * } ] ] ]\n\nNote that in this syntax, BINARY and CSV are treated as independent keywords, not as\narguments of a FORMAT option.\n\nThe following syntax was used before PostgreSQL version 7.3 and is still supported:\n\nCOPY [ BINARY ] tablename\nFROM { 'filename' | STDIN }\n[ [USING] DELIMITERS 'delimitercharacter' ]\n[ WITH NULL AS 'nullstring' ]\n\nCOPY [ BINARY ] tablename\nTO { 'filename' | STDOUT }\n[ [USING] DELIMITERS 'delimitercharacter' ]\n[ WITH NULL AS 'nullstring' ]\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "Section 28.4.6\n\n\n\nPostgreSQL 14.23                                2026                                         COPY(7)",
            "subsections": []
        }
    },
    "summary": "COPY - copy data between a file and a table",
    "flags": [],
    "examples": [
        "The following example copies a table to the client using the vertical bar (|) as the field",
        "delimiter:",
        "COPY country TO STDOUT (DELIMITER '|');",
        "To copy data from a file into the country table:",
        "COPY country FROM '/usr1/proj/bray/sql/countrydata';",
        "To copy into a file just the countries whose names start with 'A':",
        "COPY (SELECT * FROM country WHERE countryname LIKE 'A%') TO '/usr1/proj/bray/sql/alistcountries.copy';",
        "To copy into a compressed file, you can pipe the output through an external compression",
        "program:",
        "COPY country TO PROGRAM 'gzip > /usr1/proj/bray/sql/countrydata.gz';",
        "Here is a sample of data suitable for copying into a table from STDIN:",
        "AF      AFGHANISTAN",
        "AL      ALBANIA",
        "DZ      ALGERIA",
        "ZM      ZAMBIA",
        "ZW      ZIMBABWE",
        "Note that the white space on each line is actually a tab character.",
        "The following is the same data, output in binary format. The data is shown after filtering",
        "through the Unix utility od -c. The table has three columns; the first has type char(2), the",
        "second has type text, and the third has type integer. All the rows have a null value in the",
        "third column.",
        "0000000   P   G   C   O   P   Y  \\n 377  \\r  \\n  \\0  \\0  \\0  \\0  \\0  \\0",
        "0000020  \\0  \\0  \\0  \\0 003  \\0  \\0  \\0 002   A   F  \\0  \\0  \\0 013   A",
        "0000040   F   G   H   A   N   I   S   T   A   N 377 377 377 377  \\0 003",
        "0000060  \\0  \\0  \\0 002   A   L  \\0  \\0  \\0 007   A   L   B   A   N   I",
        "0000100   A 377 377 377 377  \\0 003  \\0  \\0  \\0 002   D   Z  \\0  \\0  \\0",
        "0000120 007   A   L   G   E   R   I   A 377 377 377 377  \\0 003  \\0  \\0",
        "0000140  \\0 002   Z   M  \\0  \\0  \\0 006   Z   A   M   B   I   A 377 377",
        "0000160 377 377  \\0 003  \\0  \\0  \\0 002   Z   W  \\0  \\0  \\0  \\b   Z   I",
        "0000200   M   B   A   B   W   E 377 377 377 377 377 377"
    ],
    "see_also": []
}