.\\" auto-generated by docbook2man-spec $Revision: 1.25 $
.TH "COPY" "l" "2002-11-22" "SQL - Language Statements" "SQL Commands"
.SH NAME
COPY \- copy data between files and tables
.SH SYNOPSIS
.sp
.nf
COPY \fItable\fR [ ( \fIcolumn\fR [, ...] ) ]
    FROM { '\fIfilename\fR' | \fIstdin\fR }
    [ [ WITH ] 
          [ BINARY ] 
          [ OIDS ]
          [ DELIMITER [ AS ] '\fIdelimiter\fR' ]
          [ NULL [ AS ] '\fInull string\fR' ] ]
COPY \fItable\fR [ ( \fIcolumn\fR [, ...] ) ]
    TO { '\fIfilename\fR' | \fIstdout\fR }
    [ [ WITH ] 
          [ BINARY ]
          [ OIDS ]
          [ DELIMITER [ AS ] '\fIdelimiter\fR' ]
          [ NULL [ AS ] '\fInull string\fR' ] ]
  
.sp
.fi
.SS "INPUTS"
.PP
.TP
\fB\fItable\fB\fR
The name (possibly 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 Unix path name of the input or output file.
.TP
\fB\fIstdin\fB\fR
Specifies that input comes from the client application.
.TP
\fB\fIstdout\fB\fR
Specifies that output goes to the client application.
.TP
\fBBINARY\fR
Changes the behavior of field formatting, forcing all data to be
stored or read in binary format rather than as text. You can not
specify \fBDELIMITER\fR or \fBNULL\fR
in binary mode.
.TP
\fBOIDS\fR
Specifies copying the internal object id (OID) for each row.
.TP
\fB\fIdelimiter\fB\fR
The single character that separates fields within each row (line) of the file.
.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 copy in, 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 on copy out.
.RE
.sp
.PP
.SS "OUTPUTS"
.PP
.TP
\fBCOPY\fR
The copy completed successfully.
.TP
\fBERROR: \fIreason\fB\fR
The copy failed for the reason stated in the error message.
.PP
.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 backend to directly read from
or write to a file. The file must be accessible to the backend and
the name must be specified from the viewpoint of the backend. When
\fIstdin\fR or \fIstdout\fR is
specified, data flows through the client frontend to the backend.
.sp
.RS
.B "Tip:"
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 backend when \fB\\copy\fR is used.
.RE
.sp
.SS "NOTES"
.PP
\fBCOPY\fR can only be used with plain tables, not with
views.
.PP
The BINARY keyword will force all data to be
stored/read as binary format rather than as text. It is
somewhat faster than the normal copy command, but a binary copy
file is not portable across machine architectures.
.PP
By default, a text copy uses a tab ("\\t") character as a delimiter
between fields. The field delimiter may be changed to any other
single character with the keyword \fBDELIMITER\fR. Characters
in data fields that happen to match the delimiter character will be
backslash quoted.
.PP
You must have \fIselect privilege\fR on any table
whose values are read by \fBCOPY TO\fR, and
\fIinsert privilege\fR on a table into which values
are being inserted by \fBCOPY FROM\fR. The backend also
needs appropriate Unix permissions for any file read or written by
\fBCOPY\fR.
.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 relation 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.
.PP
Files named in a \fBCOPY\fR command are read or written
directly by the backend, 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 \fBPostgreSQL\fR 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 backend has privileges to access.
.sp
.RS
.B "Tip:"
The
\fBpsql\fR instruction \fB\\copy\fR
reads or writes files on the client machine with the client's
permissions, so it is not restricted to superusers.
.RE
.sp
.PP
It is recommended that the file name used in \fBCOPY\fR
always be specified as an absolute path. This is enforced by the
backend 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 backend's working directory (somewhere below
\fI$PGDATA\fR), not the client's working directory.
.SH "FILE FORMATS"
.SS "TEXT FORMAT"
.PP
When \fBCOPY\fR is used without the BINARY option,
the file read or written is a text file with one line per table row.
Columns (attributes) in a row are separated by the delimiter character.
The attribute values themselves are strings generated by the
output function, or acceptable to the input function, of each
attribute's data type. The specified null-value string is used in
place of attributes 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.
.PP
If OIDS is specified, the OID is read or written as the first column,
preceding the user data columns. (An error is raised if OIDS is
specified for a table that does not have OIDs.)
.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 Unix file, since the end of file
serves perfectly well; but an end marker must be provided when copying
data to or from a client application.
.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 an attribute value: backslash itself,
newline, and the current delimiter character.
.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
Never put a backslash before a data character N or period
(.). Such pairs will be mistaken for the default null string
or the end-of-data marker, respectively. Any other backslashed character
that is not mentioned in the above table will be taken to represent itself.
.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
(PostgreSQL 7.2 and older versions) it is
possible to represent a data carriage return without any special quoting,
and to represent a data newline by a backslash and newline. However,
these representations will not be accepted by default in future releases.
.PP
Note that the end of each row is marked by a Unix-style newline
("\\n"). Presently, \fBCOPY FROM\fR will not behave as
desired if given a file containing DOS- or Mac-style newlines.
This is expected to change in future releases.
.SS "BINARY FORMAT"
.PP
The file format used for \fBCOPY BINARY\fR changed in
\fBPostgreSQL\fR v7.1. The new format consists
of a file header, zero or more tuples, and a file trailer.
.SS "FILE HEADER"
.PP
The file header consists of 24 bytes of fixed fields, followed
by a variable-length header extension area. The fixed fields are:
.TP
\fBSignature\fR
12-byte sequence PGBCOPY\\n\\377\\r\\n\\0 --- note that the null
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 newline-translation
filters, dropped nulls, dropped high bits, or parity changes.)
.TP
\fBInteger layout field\fR
int32 constant 0x01020304 in source's byte order. Potentially, a reader
could engage in byte-flipping of subsequent fields if the wrong byte
order is detected here.
.TP
\fBFlags field\fR
int32 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
with source's endianness, as are all subsequent integer fields. 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 dump; if 0, not
.RE
.PP
.TP
\fBHeader extension area length\fR
int32 length in bytes of remainder of header, not including self. In
the initial version this will be 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 an int16 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 an int16 \fBtyplen\fR word possibly followed by field data.
The \fBtyplen\fR field is interpreted thus:
.TP
\fBZero\fR
Field is NULL. No data follows.
.TP
\fB> 0\fR
Field is a fixed-length data type. Exactly N
bytes of data follow the \fBtyplen\fR word.
.TP
\fB-1\fR
Field is a varlena data type. The next four
bytes are the varlena header, which contains
the total value length including itself.
.TP
\fB< -1\fR
Reserved for future use.
.PP
.PP
For non-NULL fields, the reader can check that the \fBtyplen\fR matches the
expected \fBtyplen\fR for the destination column. This provides a simple
but very useful check that the data is as expected.
.PP
There is no alignment padding or any other extra data between fields.
Note also that the format does not distinguish whether a data type is
pass-by-reference or pass-by-value. Both of these provisions are
deliberate: they might help improve portability of the files (although
of course endianness and floating-point-format issues can still keep
you from moving a binary file across machines).
.PP
If OIDs are included in the dump, 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 \fBtyplen\fR --- 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 an int16 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 "USAGE"
.PP
The following example copies a table to standard output,
using a vertical bar (|) as the field delimiter:
.sp
.nf
COPY country TO \fIstdout\fR WITH DELIMITER '|';
  
.sp
.fi
.PP
To copy data from a Unix 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
\fIstdin\fR (so it has the termination sequence on the
last line):
.sp
.nf
AF      AFGHANISTAN
AL      ALBANIA
DZ      ALGERIA
ZM      ZAMBIA
ZW      ZIMBABWE
\\.
  
.sp
.fi
.PP
Note that the white space on each line is actually a TAB.
.PP
The following is the same data, output in binary format on a
Linux/i586 machine. The data is shown after filtering through the
Unix utility \fBod -c\fR. The table has three fields;
the first is \fBchar(2)\fR, the second is \fBtext\fR,
and the third is \fBinteger\fR. All the rows have a null value
in the third field.
.sp
.nf
0000000   P   G   B   C   O   P   Y  \\n 377  \\r  \\n  \\0 004 003 002 001
0000020  \\0  \\0  \\0  \\0  \\0  \\0  \\0  \\0 003  \\0 377 377 006  \\0  \\0  \\0
0000040   A   F 377 377 017  \\0  \\0  \\0   A   F   G   H   A   N   I   S
0000060   T   A   N  \\0  \\0 003  \\0 377 377 006  \\0  \\0  \\0   A   L 377
0000100 377  \\v  \\0  \\0  \\0   A   L   B   A   N   I   A  \\0  \\0 003  \\0
0000120 377 377 006  \\0  \\0  \\0   D   Z 377 377  \\v  \\0  \\0  \\0   A   L
0000140   G   E   R   I   A  \\0  \\0 003  \\0 377 377 006  \\0  \\0  \\0   Z
0000160   M 377 377  \\n  \\0  \\0  \\0   Z   A   M   B   I   A  \\0  \\0 003
0000200  \\0 377 377 006  \\0  \\0  \\0   Z   W 377 377  \\f  \\0  \\0  \\0   Z
0000220   I   M   B   A   B   W   E  \\0  \\0 377 377
  
.sp
.fi
.SH "COMPATIBILITY"
.SS "SQL92"
.PP
There is no \fBCOPY\fR statement in SQL92.
.PP
The following syntax was used by pre-7.3 applications and is still supported:
.sp
.nf
    COPY [ BINARY ] \fItable\fR [ WITH OIDS ]
        FROM { '\fIfilename\fR' | \fIstdin\fR }
        [ [USING] DELIMITERS '\fIdelimiter\fR' ]
        [ WITH NULL AS '\fInull string\fR' ]
    COPY [ BINARY ] \fItable\fR [ WITH OIDS ]
        TO { '\fIfilename\fR' | \fIstdout\fR }
        [ [USING] DELIMITERS '\fIdelimiter\fR' ]
        [ WITH NULL AS '\fInull string\fR' ]
    
.sp
.fi
