.\\" auto-generated by docbook2man-spec $Revision: 1.1.1.1 $
.TH "COPY" "" "2007-09-16" "SQL - Language Statements" "SQL Commands"
.SH NAME
COPY \- copy data between a file and a table

.SH SYNOPSIS
.sp
.nf
COPY \fItablename\fR [ ( \fIcolumn\fR [, ...] ) ]
    FROM { '\fIfilename\fR' | STDIN }
    [ [ WITH ] 
          [ BINARY ] 
          [ OIDS ]
          [ DELIMITER [ AS ] '\fIdelimiter\fR' ]
          [ NULL [ AS ] '\fInull string\fR' ] ]

COPY \fItablename\fR [ ( \fIcolumn\fR [, ...] ) ]
    TO { '\fIfilename\fR' | STDOUT }
    [ [ WITH ] 
          [ BINARY ]
          [ OIDS ]
          [ DELIMITER [ AS ] '\fIdelimiter\fR' ]
          [ NULL [ AS ] '\fInull string\fR' ] ]
.sp
.fi
.SH "DESCRIPTION"
.PP
\fBCOPY\fR moves data between
PostgreSQL tables and standard file-system
files. \fBCOPY TO\fR copies the contents of a table
\fBto\fR a file, while \fBCOPY FROM\fR copies
data \fBfrom\fR a file to a table (appending the data to
whatever is in the table already).
.PP
If a list of columns is specified, \fBCOPY\fR will
only 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,
\fBCOPY FROM\fR will insert the default values for
those columns.
.PP
\fBCOPY\fR with a file name instructs the
PostgreSQL server to directly read from
or write to a file. The file must be accessible to the server and
the name must be specified from the viewpoint of the server. When
STDIN or STDOUT is
specified, data is transmitted via the connection between the
client and the server.
.SH "PARAMETERS"
.TP
\fB\fItablename\fB\fR
The name (optionally schema-qualified) of an existing table.
.TP
\fB\fIcolumn\fB\fR
An optional list of columns to be copied. If no column list is
specified, all columns will be used.
.TP
\fB\fIfilename\fB\fR
The absolute path name of the input or output file.
.TP
\fBSTDIN\fR
Specifies that input comes from the client application.
.TP
\fBSTDOUT\fR
Specifies that output goes to the client application.
.TP
\fBBINARY\fR
Causes all data to be stored or read in binary format rather
than as text. You cannot specify the \fBDELIMITER\fR
or \fBNULL\fR options in binary mode.
.TP
\fBOIDS\fR
Specifies copying the OID for each row. (An error is raised if
OIDS is specified for a table that does not
have OIDs.)
.TP
\fB\fIdelimiter\fB\fR
The single character that separates columns within each row
(line) of the file. The default is a tab character.
.TP
\fB\fInull string\fB\fR
The string that represents a null value. The default is
\\N (backslash-N). You might prefer an empty
string, for example.
.sp
.RS
.B "Note:"
On a \fBCOPY FROM\fR, any data item that matches
this string will be stored as a null value, so you should make
sure that you use the same string as you used with
\fBCOPY TO\fR.
.RE
.sp
.SH "NOTES"
.PP
\fBCOPY\fR can only be used with plain tables, not
with views.
.PP
The BINARY key word causes all data to be
stored/read as binary format rather than as text. It is
somewhat faster than the normal text mode, but a binary-format
file is less portable across machine architectures and
PostgreSQL versions.
.PP
You must have select privilege on the table
whose values are read by \fBCOPY TO\fR, and
insert privilege on the table into which values
are inserted by \fBCOPY FROM\fR.
.PP
Files named in a \fBCOPY\fR command are read or written
directly 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 writable
by the PostgreSQL user (the user ID the
server runs as), not the client. \fBCOPY\fR naming a
file is only allowed to database superusers, since it allows reading
or writing any file that the server has privileges to access.
.PP
Do not confuse \fBCOPY\fR with the
\fBpsql\fR instruction
\fB\\copy\fR. \fB\\copy\fR invokes
\fBCOPY FROM STDIN\fR or \fBCOPY TO
STDOUT\fR, and then fetches/stores the data in a file
accessible to the \fBpsql\fR client. Thus,
file accessibility and access rights depend on the client rather
than the server when \fB\\copy\fR is used.
.PP
It is recommended that the file name used in \fBCOPY\fR
always be specified as an absolute path. This is enforced by the
server in the case of \fBCOPY TO\fR, but for
\fBCOPY FROM\fR you do have the option of reading from
a file specified by a relative path. The path will be interpreted
relative to the working directory of the server process (somewhere below
the data directory), not the client's working directory.
.PP
\fBCOPY FROM\fR will invoke any triggers and check
constraints on the destination table. However, it will not invoke rules.
.PP
\fBCOPY\fR stops operation at the first error. This
should not lead to problems in the event of a \fBCOPY
TO\fR, but the target table will already have received
earlier rows in a \fBCOPY FROM\fR. These rows will not
be visible or accessible, but they still occupy disk space. This may
amount to a considerable amount of wasted disk space if the failure
happened well into a large copy operation. You may wish to invoke
\fBVACUUM\fR to recover the wasted space.
.SH "FILE FORMATS"
.SS "TEXT FORMAT"
.PP
When \fBCOPY\fR 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 the
output function, or acceptable to the input function, of each
attribute's data type. The specified null string is used in
place of columns that are null.
\fBCOPY FROM\fR will raise an error if any line of the
input 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.
.PP
End of data can be represented by a single line containing just
backslash-period (\\.). An end-of-data marker is
not necessary when reading from a file, since the end of file
serves perfectly well; it is needed only when copying data to or from
client applications using pre-3.0 client protocol.
.PP
Backslash characters (\\) may be used in the
\fBCOPY\fR data to quote data characters that might
otherwise be taken as row or column delimiters. In particular, the
following characters \fBmust\fR be preceded by a backslash if
they appear as part of a column value: backslash itself,
newline, carriage return, and the current delimiter character.
.PP
The specified null string is sent by \fBCOPY TO\fR without
adding any backslashes; conversely, \fBCOPY FROM\fR matches
the input against the null string before removing backslashes. Therefore,
a null string such as \\N cannot be confused with
the actual data value \\N (which would be represented
as \\\\N).
.PP
The following special backslash sequences are recognized by
\fBCOPY FROM\fR:
SequenceRepresents\\bBackspace (ASCII 8)\\fForm feed (ASCII 12)\\nNewline (ASCII 10)\\rCarriage return (ASCII 13)\\tTab (ASCII 9)\\vVertical tab (ASCII 11)\\\fIdigits\fRBackslash followed by one to three octal digits specifies
the character with that numeric code
Presently, \fBCOPY TO\fR will never emit an octal-digits
backslash sequence, but it does use the other sequences listed above
for those control characters.
.PP
Any other backslashed character that is not mentioned in the above table
will be taken to represent itself. However, beware of adding backslashes
unnecessarily, since that might accidentally produce a string matching the
end-of-data marker (\\.) or the null string (\\N by
default). These strings will be recognized before any other backslash
processing is done.
.PP
It is strongly recommended that applications generating COPY data convert
data newlines and carriage returns to the \\n and
\\r sequences respectively. At present it is
possible to represent a data carriage return by a backslash and carriage
return, 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 is
transferred across different machines (for example, from Unix to Windows
or vice versa).
.PP
\fBCOPY TO\fR will terminate each row with a Unix-style 
newline (``\\n''). Servers running on MS Windows instead
output carriage return/newline (``\\r\\n''), but only for
\fBCOPY\fR to a server file; for consistency across platforms,
\fBCOPY TO STDOUT\fR always sends ``\\n''
regardless of server platform.
\fBCOPY FROM\fR can handle lines ending with newlines,
carriage returns, or carriage return/newlines. To reduce the risk of
error due to un-backslashed newlines or carriage returns that were
meant as data, \fBCOPY FROM\fR will complain if the line
endings in the input are not all alike.
.SS "BINARY FORMAT"
.PP
The file format used for \fBCOPY BINARY\fR changed in
PostgreSQL 7.4. The new format consists
of a file header, zero or more tuples containing the row data, and
a file trailer. Headers and data are now in network byte order.
.SS "FILE HEADER"
.PP
The file header consists of 15 bytes of fixed fields, followed
by a variable-length header extension area. The fixed fields are:
.TP
\fBSignature\fR
11-byte sequence PGCOPY\\n\\377\\r\\n\\0 --- note that the zero byte
is a required part of the signature. (The signature is designed to allow
easy identification of files that have been munged by a non-8-bit-clean
transfer. This signature will be changed by end-of-line-translation
filters, dropped zero bytes, dropped high bits, or parity changes.)
.TP
\fBFlags field\fR
32-bit integer bit mask to denote important aspects of the file format. Bits
are numbered from 0 (LSB) to 31 (MSB). Note that
this field is stored in network byte order (most significant byte first),
as are all the integer fields used in the file format. Bits
16-31 are reserved to denote critical file format issues; a reader
should abort if it finds an unexpected bit set in this range. Bits 0-15
are reserved to signal backwards-compatible format issues; a reader
should simply ignore any unexpected bits set in this range. Currently
only one flag bit is defined, and the rest must be zero:
.RS
.TP
\fBBit 16\fR
if 1, OIDs are included in the data; if 0, not
.RE
.PP
.TP
\fBHeader extension area length\fR
32-bit integer, length in bytes of remainder of header, not including self.
Currently, this is zero, and the first tuple follows
immediately. Future changes to the format might allow additional data
to be present in the header. A reader should silently skip over any header
extension data it does not know what to do with.
.PP
.PP
The header extension area is envisioned to contain a sequence of
self-identifying chunks. The flags field is not intended to tell readers
what is in the extension area. Specific design of header extension contents
is left for a later release.
.PP
This design allows for both backwards-compatible header additions (add
header extension chunks, or set low-order flag bits) and
non-backwards-compatible changes (set high-order flag bits to signal such
changes, and add supporting data to the extension area if needed).
.SS "TUPLES"
.PP
Each tuple begins with a 16-bit integer count of the number of fields in the
tuple. (Presently, all tuples in a table will have the same count, but that
might not always be true.) Then, repeated for each field in the tuple, there
is a 32-bit length word followed by that many bytes of field data. (The
length 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.
.PP
There is no alignment padding or any other extra data between fields.
.PP
Presently, all data values in a \fBCOPY BINARY\fR file are
assumed to be in binary format (format code one). It is anticipated that a
future extension may add a header field that allows per-column format codes
to be specified.
.PP
To determine the appropriate binary format for the actual tuple data you
should consult the PostgreSQL source, in
particular the \fB*send\fR and \fB*recv\fR functions for
each column's data type (typically these functions are found in the
\fIsrc/backend/utils/adt/\fR directory of the source
distribution).
.PP
If OIDs are included in the file, the OID field immediately follows the
field-count word. It is a normal field except that it's not included
in the field-count. In particular it has a length word --- this will allow
handling of 4-byte vs. 8-byte OIDs without too much pain, and will allow
OIDs to be shown as null if that ever proves desirable.
.SS "FILE TRAILER"
.PP
The file trailer consists of a 16-bit integer word containing -1. This
is easily distinguished from a tuple's field-count word.
.PP
A reader should report an error if a field-count word is neither -1
nor the expected number of columns. This provides an extra
check against somehow getting out of sync with the data.
.SH "EXAMPLES"
.PP
The following example copies a table to the client
using the vertical bar (|) as the field delimiter:
.sp
.nf
COPY country TO STDOUT WITH DELIMITER '|';
.sp
.fi
.PP
To copy data from a file into the country table:
.sp
.nf
COPY country FROM '/usr1/proj/bray/sql/country_data';
.sp
.fi
.PP
Here is a sample of data suitable for copying into a table from
STDIN:
.sp
.nf
AF      AFGHANISTAN
AL      ALBANIA
DZ      ALGERIA
ZM      ZAMBIA
ZW      ZIMBABWE
.sp
.fi
Note that the white space on each line is actually a tab character.
.PP
The following is the same data, output in binary format.
The data is shown after filtering through the
Unix utility \fBod -c\fR. The table has three columns;
the first has type \fBchar(2)\fR, the second has type \fBtext\fR,
and the third has type \fBinteger\fR. All the rows have a null value
in the third column.
.sp
.nf
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
.sp
.fi
.SH "COMPATIBILITY"
.PP
There is no \fBCOPY\fR statement in the SQL standard.
.PP
The following syntax was used before PostgreSQL version 7.3 and is
still supported:
.sp
.nf
COPY [ BINARY ] \fItablename\fR [ WITH OIDS ]
    FROM { '\fIfilename\fR' | STDIN }
    [ [USING] DELIMITERS '\fIdelimiter\fR' ]
    [ WITH NULL AS '\fInull string\fR' ]

COPY [ BINARY ] \fItablename\fR [ WITH OIDS ]
    TO { '\fIfilename\fR' | STDOUT }
    [ [USING] DELIMITERS '\fIdelimiter\fR' ]
    [ WITH NULL AS '\fInull string\fR' ]
.sp
.fi
