man copy howto postgresql-7.4.11-1.FC3.1.x86_64.rpm (2023)

man copy howto postgresql-7.4.11-1.FC3.1.x86_64.rpm (1)

MAN page from Fedora3 postgresql-7.4.11-1.FC3.1.x86_64.rpm

Section: SQL Commands (7)
Updated: 2003-11-02


COPY - copy data between a file and a table


COPY tablename [ ( column [, ...] ) ] FROM { 'filename' | STDIN } [ [ WITH ] [ BINARY ] [ OIDS ] [ DELIMITER [ AS ] 'delimiter' ] [ NULL [ AS ] 'null string' ] ]COPY tablename [ ( column [, ...] ) ] TO { 'filename' | STDOUT } [ [ WITH ] [ BINARY ] [ OIDS ] [ DELIMITER [ AS ] 'delimiter' ] [ NULL [ AS ] 'null string' ] ]


COPY moves data betweenPostgreSQL tables and standard file-systemfiles. COPY TO copies the contents of a tableto a file, while COPY FROM copiesdata from a file to a table (appending the data towhatever is in the table already).

If a list of columns is specified, COPY willonly copy the data in the specified columns to or from the file.If there are any columns in the table that are not in the column list,COPY FROM will insert the default values forthose columns.

COPY with a file name instructs thePostgreSQL server to directly read fromor write to a file. The file must be accessible to the server andthe name must be specified from the viewpoint of the server. WhenSTDIN or STDOUT isspecified, data is transmitted via the connection between theclient and the server.


The name (optionally schema-qualified) of an existing table.
An optional list of columns to be copied. If no column list isspecified, all columns will be used.
The absolute path name of the input or output file.
Specifies that input comes from the client application.
Specifies that output goes to the client application.
Causes all data to be stored or read in binary format ratherthan as text. You cannot specify the DELIMITERor NULL options in binary mode.
Specifies copying the OID for each row. (An error is raised ifOIDS is specified for a table that does nothave OIDs.)
The single character that separates columns within each row(line) of the file. The default is a tab character.
null string
The string that represents a null value. The default is\N (backslash-N). You might prefer an emptystring, for example.
Note:On a COPY FROM, any data item that matchesthis string will be stored as a null value, so you should makesure that you use the same string as you used withCOPY TO.


COPY can only be used with plain tables, notwith views.

The BINARY key word causes all data to bestored/read as binary format rather than as text. It issomewhat faster than the normal text mode, but a binary-formatfile is less portable across machine architectures andPostgreSQL versions.

You must have select privilege on the tablewhose values are read by COPY TO, andinsert privilege on the table into which valuesare inserted by COPY FROM.

Files named in a COPY command are read or writtendirectly by the server, not by the client application. Therefore,they must reside on or be accessible to the database server machine,not the client. They must be accessible to and readable or writableby the PostgreSQL user (the user ID theserver runs as), not the client. COPY naming afile is only allowed to database superusers, since it allows readingor writing any file that the server has privileges to access.

Do not confuse COPY with thepsql instruction\copy. \copy invokesCOPY FROM STDIN or COPY TOSTDOUT, and then fetches/stores the data in a fileaccessible to the psql client. Thus,file accessibility and access rights depend on the client ratherthan the server when \copy is used.

It is recommended that the file name used in COPYalways be specified as an absolute path. This is enforced by theserver in the case of COPY TO, but forCOPY FROM you do have the option of reading froma file specified by a relative path. The path will be interpretedrelative to the working directory of the server process (somewhere belowthe data directory), not the client's working directory.

COPY FROM will invoke any triggers and checkconstraints on the destination table. However, it will not invoke rules.

COPY stops operation at the first error. Thisshould not lead to problems in the event of a COPYTO, but the target table will already have receivedearlier rows in a COPY FROM. These rows will notbe visible or accessible, but they still occupy disk space. This mayamount to a considerable amount of wasted disk space if the failurehappened well into a large copy operation. You may wish to invokeVACUUM to recover the wasted space.



When COPY is used without the BINARY option,the data read or written is a text file with one line per table row.Columns in a row are separated by the delimiter character.The column values themselves are strings generated by theoutput function, or acceptable to the input function, of eachattribute's data type. The specified null string is used inplace of columns that are null.COPY FROM will raise an error if any line of theinput file contains more or fewer columns than are expected.If OIDS is specified, the OID is read or written as the first column,preceding the user data columns.

End of data can be represented by a single line containing justbackslash-period (\.). An end-of-data marker isnot necessary when reading from a file, since the end of fileserves perfectly well; it is needed only when copying data to or fromclient applications using pre-3.0 client protocol.

Backslash characters (\) may be used in theCOPY data to quote data characters that mightotherwise be taken as row or column delimiters. In particular, thefollowing characters must be preceded by a backslash ifthey appear as part of a column value: backslash itself,newline, carriage return, and the current delimiter character.

The specified null string is sent by COPY TO withoutadding any backslashes; conversely, COPY FROM matchesthe input against the null string before removing backslashes. Therefore,a null string such as \N cannot be confused withthe actual data value \N (which would be representedas \\N).

The following special backslash sequences are recognized byCOPY FROM:SequenceRepresents\bBackspace (ASCII 8)\fForm feed (ASCII 12)\nNewline (ASCII 10)\rCarriage return (ASCII 13)\tTab (ASCII 9)\vVertical tab (ASCII 11)\digitsBackslash followed by one to three octal digits specifiesthe character with that numeric codePresently, COPY TO will never emit an octal-digitsbackslash sequence, but it does use the other sequences listed abovefor those control characters.

Any other backslashed character that is not mentioned in the above tablewill be taken to represent itself. However, beware of adding backslashesunnecessarily, since that might accidentally produce a string matching theend-of-data marker (\.) or the null string (\N bydefault). These strings will be recognized before any other backslashprocessing is done.

It is strongly recommended that applications generating COPY data convertdata newlines and carriage returns to the \n and\r sequences respectively. At present it ispossible to represent a data carriage return by a backslash and carriagereturn, and to represent a data newline by a backslash and newline. However, these representations might not be accepted in future releases.They are also highly vulnerable to corruption if the COPY file istransferred across different machines (for example, from Unix to Windowsor vice versa).

COPY TO will terminate each row with a Unix-style newline (``\n''). Servers running on MS Windows insteadoutput carriage return/newline (``\r\n''), but only forCOPY to a server file; for consistency across platforms,COPY TO STDOUT always sends ``\n''regardless of server platform.COPY FROM can handle lines ending with newlines,carriage returns, or carriage return/newlines. To reduce the risk oferror due to un-backslashed newlines or carriage returns that weremeant as data, COPY FROM will complain if the lineendings in the input are not all alike.


The file format used for COPY BINARY changed inPostgreSQL 7.4. The new format consistsof a file header, zero or more tuples containing the row data, anda file trailer. Headers and data are now in network byte order.


The file header consists of 15 bytes of fixed fields, followedby a variable-length header extension area. The fixed fields are:

11-byte sequence PGCOPY\n\377\r\n\0 --- note that the zero byteis a required part of the signature. (The signature is designed to alloweasy identification of files that have been munged by a non-8-bit-cleantransfer. This signature will be changed by end-of-line-translationfilters, dropped zero bytes, dropped high bits, or parity changes.)
Flags field
32-bit integer bit mask to denote important aspects of the file format. Bitsare numbered from 0 (LSB) to 31 (MSB). Note thatthis field is stored in network byte order (most significant byte first),as are all the integer fields used in the file format. Bits16-31 are reserved to denote critical file format issues; a readershould abort if it finds an unexpected bit set in this range. Bits 0-15are reserved to signal backwards-compatible format issues; a readershould simply ignore any unexpected bits set in this range. Currentlyonly one flag bit is defined, and the rest must be zero:
Bit 16
if 1, OIDs are included in the data; if 0, not
Header extension area length
32-bit integer, length in bytes of remainder of header, not including self.Currently, this is zero, and the first tuple followsimmediately. Future changes to the format might allow additional datato be present in the header. A reader should silently skip over any headerextension data it does not know what to do with.

The header extension area is envisioned to contain a sequence ofself-identifying chunks. The flags field is not intended to tell readerswhat is in the extension area. Specific design of header extension contentsis left for a later release.

This design allows for both backwards-compatible header additions (addheader extension chunks, or set low-order flag bits) andnon-backwards-compatible changes (set high-order flag bits to signal suchchanges, and add supporting data to the extension area if needed).


Each tuple begins with a 16-bit integer count of the number of fields in thetuple. (Presently, all tuples in a table will have the same count, but thatmight not always be true.) Then, repeated for each field in the tuple, thereis a 32-bit length word followed by that many bytes of field data. (Thelength word does not include itself, and can be zero.) As a special case,-1 indicates a NULL field value. No value bytes follow in the NULL case.

There is no alignment padding or any other extra data between fields.

Presently, all data values in a COPY BINARY file areassumed to be in binary format (format code one). It is anticipated that afuture extension may add a header field that allows per-column format codesto be specified.

To determine the appropriate binary format for the actual tuple data youshould consult the PostgreSQL source, inparticular the *send and *recv functions foreach column's data type (typically these functions are found in thesrc/backend/utils/adt/ directory of the sourcedistribution).

If OIDs are included in the file, the OID field immediately follows thefield-count word. It is a normal field except that it's not includedin the field-count. In particular it has a length word --- this will allowhandling of 4-byte vs. 8-byte OIDs without too much pain, and will allowOIDs to be shown as null if that ever proves desirable.


The file trailer consists of a 16-bit integer word containing -1. Thisis easily distinguished from a tuple's field-count word.

A reader should report an error if a field-count word is neither -1nor the expected number of columns. This provides an extracheck against somehow getting out of sync with the data.


The following example copies a table to the clientusing the vertical bar (|) as the field delimiter:


To copy data from a file into the country table:

COPY country FROM '/usr1/proj/bray/sql/country_data';

Here is a sample of data suitable for copying into a table fromSTDIN:


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 theUnix 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 valuein the third column.

0000000 P G C O P Y \n 377 \r \n \0 \0 \0 \0 \0 \00000020 \0 \0 \0 \0 003 \0 \0 \0 002 A F \0 \0 \0 013 A0000040 F G H A N I S T A N 377 377 377 377 \0 0030000060 \0 \0 \0 002 A L \0 \0 \0 007 A L B A N I0000100 A 377 377 377 377 \0 003 \0 \0 \0 002 D Z \0 \0 \00000120 007 A L G E R I A 377 377 377 377 \0 003 \0 \00000140 \0 002 Z M \0 \0 \0 006 Z A M B I A 377 3770000160 377 377 \0 003 \0 \0 \0 002 Z W \0 \0 \0 \b Z I0000200 M B A B W E 377 377 377 377 377 377


There is no COPY statement in the SQL standard.

The following syntax was used before PostgreSQL version 7.3 and isstill supported:

COPY [ BINARY ] tablename [ WITH OIDS ] FROM { 'filename' | STDIN } [ [USING] DELIMITERS 'delimiter' ] [ WITH NULL AS 'null string' ]COPY [ BINARY ] tablename [ WITH OIDS ] TO { 'filename' | STDOUT } [ [USING] DELIMITERS 'delimiter' ] [ WITH NULL AS 'null string' ]



This document was created byman2html,using the manual pages.

Top Articles
Latest Posts
Article information

Author: Geoffrey Lueilwitz

Last Updated: 02/24/2023

Views: 6290

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.