2 $PostgreSQL: pgsql/doc/src/sgml/ref/copy.sgml,v 1.62 2004/12/13 18:05:10 petere Exp $
3 PostgreSQL documentation
7 <refentry id="SQL-COPY">
9 <refentrytitle id="sql-copy-title">COPY</refentrytitle>
10 <refmiscinfo>SQL - Language Statements</refmiscinfo>
14 <refname>COPY</refname>
15 <refpurpose>copy data between a file and a table</refpurpose>
18 <indexterm zone="sql-copy">
19 <primary>COPY</primary>
24 COPY <replaceable class="parameter">tablename</replaceable> [ ( <replaceable class="parameter">column</replaceable> [, ...] ) ]
25 FROM { '<replaceable class="parameter">filename</replaceable>' | STDIN }
29 [ DELIMITER [ AS ] '<replaceable class="parameter">delimiter</replaceable>' ]
30 [ NULL [ AS ] '<replaceable class="parameter">null string</replaceable>' ]
31 [ CSV [ QUOTE [ AS ] '<replaceable class="parameter">quote</replaceable>' ]
32 [ ESCAPE [ AS ] '<replaceable class="parameter">escape</replaceable>' ]
33 [ FORCE NOT NULL <replaceable class="parameter">column</replaceable> [, ...] ]
35 COPY <replaceable class="parameter">tablename</replaceable> [ ( <replaceable class="parameter">column</replaceable> [, ...] ) ]
36 TO { '<replaceable class="parameter">filename</replaceable>' | STDOUT }
40 [ DELIMITER [ AS ] '<replaceable class="parameter">delimiter</replaceable>' ]
41 [ NULL [ AS ] '<replaceable class="parameter">null string</replaceable>' ]
42 [ CSV [ QUOTE [ AS ] '<replaceable class="parameter">quote</replaceable>' ]
43 [ ESCAPE [ AS ] '<replaceable class="parameter">escape</replaceable>' ]
44 [ FORCE QUOTE <replaceable class="parameter">column</replaceable> [, ...] ]
49 <title>Description</title>
52 <command>COPY</command> moves data between
53 <productname>PostgreSQL</productname> tables and standard file-system
54 files. <command>COPY TO</command> copies the contents of a table
55 <emphasis>to</> a file, while <command>COPY FROM</command> copies
56 data <emphasis>from</> a file to a table (appending the data to
57 whatever is in the table already).
61 If a list of columns is specified, <command>COPY</command> will
62 only copy the data in the specified columns to or from the file.
63 If there are any columns in the table that are not in the column list,
64 <command>COPY FROM</command> will insert the default values for
69 <command>COPY</command> with a file name instructs the
70 <productname>PostgreSQL</productname> server to directly read from
71 or write to a file. The file must be accessible to the server and
72 the name must be specified from the viewpoint of the server. When
73 <literal>STDIN</literal> or <literal>STDOUT</literal> is
74 specified, data is transmitted via the connection between the
75 client and the server.
80 <title>Parameters</title>
84 <term><replaceable class="parameter">tablename</replaceable></term>
87 The name (optionally schema-qualified) of an existing table.
93 <term><replaceable class="parameter">column</replaceable></term>
96 An optional list of columns to be copied. If no column list is
97 specified, all columns will be used.
103 <term><replaceable class="parameter">filename</replaceable></term>
106 The absolute path name of the input or output file.
112 <term><literal>STDIN</literal></term>
115 Specifies that input comes from the client application.
121 <term><literal>STDOUT</literal></term>
124 Specifies that output goes to the client application.
130 <term><literal>BINARY</literal></term>
133 Causes all data to be stored or read in binary format rather
134 than as text. You cannot specify the <option>DELIMITER</option>
135 or <option>NULL</option> options in binary mode.
141 <term><literal>OIDS</literal></term>
144 Specifies copying the OID for each row. (An error is raised if
145 <literal>OIDS</literal> is specified for a table that does not
152 <term><replaceable class="parameter">delimiter</replaceable></term>
155 The single character that separates columns within each row
156 (line) of the file. The default is a tab character in text mode,
157 a comma in <literal>CSV</> mode.
163 <term><replaceable class="parameter">null string</replaceable></term>
166 The string that represents a null value. The default is
167 <literal>\N</literal> (backslash-N) in text mode, and a empty
168 value with no quotes in <literal>CSV</> mode. You might prefer an
169 empty string even in text mode for cases where you don't want to
170 distinguish nulls from empty strings.
175 When using <command>COPY FROM</command>, any data item that matches
176 this string will be stored as a null value, so you should make
177 sure that you use the same string as you used with
178 <command>COPY TO</command>.
186 <term><literal>CSV</literal></term>
189 Enables Comma Separated Variable (<literal>CSV</>) mode. (Also
190 called Comma Separated Value). It sets the default
191 <literal>DELIMITER</> to comma, and <literal>QUOTE</> and
192 <literal>ESCAPE</> values to double-quote.
198 <term><replaceable class="parameter">quote</replaceable></term>
201 Specifies the quotation character in <literal>CSV</> mode.
202 The default is double-quote.
208 <term><replaceable class="parameter">escape</replaceable></term>
211 Specifies the character that should appear before a
212 <literal>QUOTE</> data character value in <literal>CSV</> mode.
213 The default is the <literal>QUOTE</> value (usually double-quote).
219 <term><literal>FORCE QUOTE</></term>
222 In <literal>CSV</> <command>COPY TO</> mode, forces quoting to be
223 used for all non-<literal>NULL</> values in each specified column.
224 <literal>NULL</> output is never quoted.
230 <term><literal>FORCE NOT NULL</></term>
233 In <literal>CSV</> <command>COPY FROM</> mode, process each
234 specified column as though it were quoted and hence not a
235 <literal>NULL</> value. For the default <literal>null string</> in
236 <literal>CSV</> mode (<literal>''</>), this causes a missing
237 values to be input as a zero-length strings.
249 <command>COPY</command> can only be used with plain tables, not
254 The <literal>BINARY</literal> key word causes all data to be
255 stored/read as binary format rather than as text. It is
256 somewhat faster than the normal text mode, but a binary-format
257 file is less portable across machine architectures and
258 <productname>PostgreSQL</productname> versions.
262 You must have select privilege on the table
263 whose values are read by <command>COPY TO</command>, and
264 insert privilege on the table into which values
265 are inserted by <command>COPY FROM</command>.
269 Files named in a <command>COPY</command> command are read or written
270 directly by the server, not by the client application. Therefore,
271 they must reside on or be accessible to the database server machine,
272 not the client. They must be accessible to and readable or writable
273 by the <productname>PostgreSQL</productname> user (the user ID the
274 server runs as), not the client. <command>COPY</command> naming a
275 file is only allowed to database superusers, since it allows reading
276 or writing any file that the server has privileges to access.
280 Do not confuse <command>COPY</command> with the
281 <application>psql</application> instruction
282 <command>\copy</command>. <command>\copy</command> invokes
283 <command>COPY FROM STDIN</command> or <command>COPY TO
284 STDOUT</command>, and then fetches/stores the data in a file
285 accessible to the <application>psql</application> client. Thus,
286 file accessibility and access rights depend on the client rather
287 than the server when <command>\copy</command> is used.
291 It is recommended that the file name used in <command>COPY</command>
292 always be specified as an absolute path. This is enforced by the
293 server in the case of <command>COPY TO</command>, but for
294 <command>COPY FROM</command> you do have the option of reading from
295 a file specified by a relative path. The path will be interpreted
296 relative to the working directory of the server process (somewhere below
297 the data directory), not the client's working directory.
301 <command>COPY FROM</command> will invoke any triggers and check
302 constraints on the destination table. However, it will not invoke rules.
306 <command>COPY</command> input and output is affected by
307 <varname>DateStyle </varname>. For portability with other
308 <productname>PostgreSQL</productname> installations which might use
309 non-default <varname>DateStyle</varname> settings,
310 <varname>DateStyle</varname> should be set to <literal>ISO</> before
311 using <command>COPY</>. In <literal>CSV</> mode, use <literal>ISO</>
312 or a <varname>DateStyle</varname> setting appropriate for the
313 external application.
317 <command>COPY</command> stops operation at the first error. This
318 should not lead to problems in the event of a <command>COPY
319 TO</command>, but the target table will already have received
320 earlier rows in a <command>COPY FROM</command>. These rows will not
321 be visible or accessible, but they still occupy disk space. This may
322 amount to a considerable amount of wasted disk space if the failure
323 happened well into a large copy operation. You may wish to invoke
324 <command>VACUUM</command> to recover the wasted space.
329 <title>File Formats</title>
332 <title>Text Format</title>
335 When <command>COPY</command> is used without the <literal>BINARY</literal> option,
336 the data read or written is a text file with one line per table row,
337 unless <literal>CSV</> mode is used.
338 Columns in a row are separated by the delimiter character.
339 The column values themselves are strings generated by the
340 output function, or acceptable to the input function, of each
341 attribute's data type. The specified null string is used in
342 place of columns that are null.
343 <command>COPY FROM</command> will raise an error if any line of the
344 input file contains more or fewer columns than are expected.
345 If <literal>OIDS</literal> is specified, the OID is read or written as the first column,
346 preceding the user data columns.
350 End of data can be represented by a single line containing just
351 backslash-period (<literal>\.</>). An end-of-data marker is
352 not necessary when reading from a file, since the end of file
353 serves perfectly well; it is needed only when copying data to or from
354 client applications using pre-3.0 client protocol.
358 Backslash characters (<literal>\</>) may be used in the
359 <command>COPY</command> data to quote data characters that might
360 otherwise be taken as row or column delimiters. In particular, the
361 following characters <emphasis>must</> be preceded by a backslash if
362 they appear as part of a column value: backslash itself,
363 newline, carriage return, and the current delimiter character.
367 The specified null string is sent by <command>COPY TO</command> without
368 adding any backslashes; conversely, <command>COPY FROM</command> matches
369 the input against the null string before removing backslashes. Therefore,
370 a null string such as <literal>\N</literal> cannot be confused with
371 the actual data value <literal>\N</literal> (which would be represented
372 as <literal>\\N</literal>).
376 The following special backslash sequences are recognized by
377 <command>COPY FROM</command>:
383 <entry>Sequence</entry>
384 <entry>Represents</entry>
390 <entry><literal>\b</></entry>
391 <entry>Backspace (ASCII 8)</entry>
394 <entry><literal>\f</></entry>
395 <entry>Form feed (ASCII 12)</entry>
398 <entry><literal>\n</></entry>
399 <entry>Newline (ASCII 10)</entry>
402 <entry><literal>\r</></entry>
403 <entry>Carriage return (ASCII 13)</entry>
406 <entry><literal>\t</></entry>
407 <entry>Tab (ASCII 9)</entry>
410 <entry><literal>\v</></entry>
411 <entry>Vertical tab (ASCII 11)</entry>
414 <entry><literal>\</><replaceable>digits</></entry>
415 <entry>Backslash followed by one to three octal digits specifies
416 the character with that numeric code</entry>
422 Presently, <command>COPY TO</command> will never emit an octal-digits
423 backslash sequence, but it does use the other sequences listed above
424 for those control characters.
428 Any other backslashed character that is not mentioned in the above table
429 will be taken to represent itself. However, beware of adding backslashes
430 unnecessarily, since that might accidentally produce a string matching the
431 end-of-data marker (<literal>\.</>) or the null string (<literal>\N</> by
432 default). These strings will be recognized before any other backslash
437 It is strongly recommended that applications generating <command>COPY</command> data convert
438 data newlines and carriage returns to the <literal>\n</> and
439 <literal>\r</> sequences respectively. At present it is
440 possible to represent a data carriage return by a backslash and carriage
441 return, and to represent a data newline by a backslash and newline.
442 However, these representations might not be accepted in future releases.
443 They are also highly vulnerable to corruption if the <command>COPY</command> file is
444 transferred across different machines (for example, from Unix to Windows
449 <command>COPY TO</command> will terminate each row with a Unix-style
450 newline (<quote><literal>\n</></>). Servers running on Microsoft Windows instead
451 output carriage return/newline (<quote><literal>\r\n</></>), but only for
452 <command>COPY</> to a server file; for consistency across platforms,
453 <command>COPY TO STDOUT</> always sends <quote><literal>\n</></>
454 regardless of server platform.
455 <command>COPY FROM</command> can handle lines ending with newlines,
456 carriage returns, or carriage return/newlines. To reduce the risk of
457 error due to un-backslashed newlines or carriage returns that were
458 meant as data, <command>COPY FROM</command> will complain if the line
459 endings in the input are not all alike.
464 <title>CSV Format</title>
467 This format is used for importing and exporting the Comma
468 Separated Variable (<literal>CSV</>) file format used by many other
469 programs, such as spreadsheets. Instead of the escaping used by
470 <productname>PostgreSQL</productname>'s standard text mode, it
471 produces and recognises the common CSV escaping mechanism.
475 The values in each record are separated by the <literal>DELIMITER</>
476 character. If the value contains the delimiter character, the
477 <literal>QUOTE</> character, the <literal>NULL</> string, a carriage
478 return, or line feed character, then the whole value is prefixed and
479 suffixed by the <literal>QUOTE</> character, and any occurrence
480 within the value of a <literal>QUOTE</> character or the
481 <literal>ESCAPE</> character is preceded by the escape character.
482 You can also use <literal>FORCE QUOTE</> to force quotes when outputting
483 non-<literal>NULL</> values in specific columns.
487 In general, the <literal>CSV</> format has no way to distinguish a
488 <literal>NULL</> value from an empty string.
489 <productname>PostgreSQL</>'s <command>COPY</> handles this by
490 quoting. A <literal>NULL</> is output as the <literal>NULL</>
491 string and is not quoted, while a data value matching the
492 <literal>NULL</> string is quoted. Therefore, using the default
493 settings, a <literal>NULL</> is written as an unquoted empty
494 string, while an empty string is written with double quotes
495 (<literal>""</>). Reading values follows similar rules. You can
496 use <literal>FORCE NOT NULL</> to prevent <literal>NULL</> input
497 comparisons for specific columns.
502 CSV mode will both recognize and produce CSV files with quoted
503 values containing embedded carriage returns and line feeds. Thus
504 the files are not strictly one line per table row like text-mode
505 files. However, <productname>PostgreSQL</productname> will reject
506 <command>COPY</command> input if any fields contain embedded line
507 end character sequences that do not match the line ending
508 convention used in the CSV file itself. It is generally safer to
509 import data containing embedded line end characters using the
510 text or binary formats rather than CSV.
516 Many programs produce strange and occasionally perverse CSV files,
517 so the file format is more a convention than a standard. Thus you
518 might encounter some files that cannot be imported using this
519 mechanism, and <command>COPY</> might produce files that other
520 programs can not process.
527 <title>Binary Format</title>
530 The file format used for <command>COPY BINARY</command> changed in
531 <productname>PostgreSQL</productname> 7.4. The new format consists
532 of a file header, zero or more tuples containing the row data, and
533 a file trailer. Headers and data are now in network byte order.
537 <title>File Header</title>
540 The file header consists of 15 bytes of fixed fields, followed
541 by a variable-length header extension area. The fixed fields are:
545 <term>Signature</term>
548 11-byte sequence <literal>PGCOPY\n\377\r\n\0</> — note that the zero byte
549 is a required part of the signature. (The signature is designed to allow
550 easy identification of files that have been munged by a non-8-bit-clean
551 transfer. This signature will be changed by end-of-line-translation
552 filters, dropped zero bytes, dropped high bits, or parity changes.)
558 <term>Flags field</term>
561 32-bit integer bit mask to denote important aspects of the file format. Bits
562 are numbered from 0 (<acronym>LSB</>) to 31 (<acronym>MSB</>). Note that
563 this field is stored in network byte order (most significant byte first),
564 as are all the integer fields used in the file format. Bits
565 16-31 are reserved to denote critical file format issues; a reader
566 should abort if it finds an unexpected bit set in this range. Bits 0-15
567 are reserved to signal backwards-compatible format issues; a reader
568 should simply ignore any unexpected bits set in this range. Currently
569 only one flag bit is defined, and the rest must be zero:
575 if 1, OIDs are included in the data; if 0, not
585 <term>Header extension area length</term>
588 32-bit integer, length in bytes of remainder of header, not including self.
589 Currently, this is zero, and the first tuple follows
590 immediately. Future changes to the format might allow additional data
591 to be present in the header. A reader should silently skip over any header
592 extension data it does not know what to do with.
600 The header extension area is envisioned to contain a sequence of
601 self-identifying chunks. The flags field is not intended to tell readers
602 what is in the extension area. Specific design of header extension contents
603 is left for a later release.
607 This design allows for both backwards-compatible header additions (add
608 header extension chunks, or set low-order flag bits) and
609 non-backwards-compatible changes (set high-order flag bits to signal such
610 changes, and add supporting data to the extension area if needed).
615 <title>Tuples</title>
617 Each tuple begins with a 16-bit integer count of the number of fields in the
618 tuple. (Presently, all tuples in a table will have the same count, but that
619 might not always be true.) Then, repeated for each field in the tuple, there
620 is a 32-bit length word followed by that many bytes of field data. (The
621 length word does not include itself, and can be zero.) As a special case,
622 -1 indicates a NULL field value. No value bytes follow in the NULL case.
626 There is no alignment padding or any other extra data between fields.
630 Presently, all data values in a <command>COPY BINARY</command> file are
631 assumed to be in binary format (format code one). It is anticipated that a
632 future extension may add a header field that allows per-column format codes
637 To determine the appropriate binary format for the actual tuple data you
638 should consult the <productname>PostgreSQL</productname> source, in
639 particular the <function>*send</> and <function>*recv</> functions for
640 each column's data type (typically these functions are found in the
641 <filename>src/backend/utils/adt/</filename> directory of the source
646 If OIDs are included in the file, the OID field immediately follows the
647 field-count word. It is a normal field except that it's not included
648 in the field-count. In particular it has a length word — this will allow
649 handling of 4-byte vs. 8-byte OIDs without too much pain, and will allow
650 OIDs to be shown as null if that ever proves desirable.
655 <title>File Trailer</title>
658 The file trailer consists of a 16-bit integer word containing -1. This
659 is easily distinguished from a tuple's field-count word.
663 A reader should report an error if a field-count word is neither -1
664 nor the expected number of columns. This provides an extra
665 check against somehow getting out of sync with the data.
672 <title>Examples</title>
675 The following example copies a table to the client
676 using the vertical bar (<literal>|</literal>) as the field delimiter:
678 COPY country TO STDOUT WITH DELIMITER '|';
683 To copy data from a file into the <literal>country</> table:
685 COPY country FROM '/usr1/proj/bray/sql/country_data';
690 Here is a sample of data suitable for copying into a table from
691 <literal>STDIN</literal>:
699 Note that the white space on each line is actually a tab character.
703 The following is the same data, output in binary format.
704 The data is shown after filtering through the
705 Unix utility <command>od -c</command>. The table has three columns;
706 the first has type <type>char(2)</type>, the second has type <type>text</type>,
707 and the third has type <type>integer</type>. All the rows have a null value
710 0000000 P G C O P Y \n 377 \r \n \0 \0 \0 \0 \0 \0
711 0000020 \0 \0 \0 \0 003 \0 \0 \0 002 A F \0 \0 \0 013 A
712 0000040 F G H A N I S T A N 377 377 377 377 \0 003
713 0000060 \0 \0 \0 002 A L \0 \0 \0 007 A L B A N I
714 0000100 A 377 377 377 377 \0 003 \0 \0 \0 002 D Z \0 \0 \0
715 0000120 007 A L G E R I A 377 377 377 377 \0 003 \0 \0
716 0000140 \0 002 Z M \0 \0 \0 006 Z A M B I A 377 377
717 0000160 377 377 \0 003 \0 \0 \0 002 Z W \0 \0 \0 \b Z I
718 0000200 M B A B W E 377 377 377 377 377 377
724 <title>Compatibility</title>
727 There is no <command>COPY</command> statement in the SQL standard.
731 The following syntax was used before <productname>PostgreSQL</>
732 version 7.3 and is still supported:
735 COPY [ BINARY ] <replaceable class="parameter">tablename</replaceable> [ WITH OIDS ]
736 FROM { '<replaceable class="parameter">filename</replaceable>' | STDIN }
737 [ [USING] DELIMITERS '<replaceable class="parameter">delimiter</replaceable>' ]
738 [ WITH NULL AS '<replaceable class="parameter">null string</replaceable>' ]
740 COPY [ BINARY ] <replaceable class="parameter">tablename</replaceable> [ WITH OIDS ]
741 TO { '<replaceable class="parameter">filename</replaceable>' | STDOUT }
742 [ [USING] DELIMITERS '<replaceable class="parameter">delimiter</replaceable>' ]
743 [ WITH NULL AS '<replaceable class="parameter">null string</replaceable>' ]
749 <!-- Keep this comment at the end of the file
754 sgml-minimize-attributes:nil
755 sgml-always-quote-attributes:t
758 sgml-parent-document:nil
759 sgml-default-dtd-file:"../reference.ced"
760 sgml-exposed-tags:nil
761 sgml-local-catalogs:"/usr/lib/sgml/catalog"
762 sgml-local-ecat-files:nil