]> granicus.if.org Git - postgresql/blob - doc/src/sgml/ref/copy.sgml
Allow psql to print COPY command status in more cases.
[postgresql] / doc / src / sgml / ref / copy.sgml
1 <!--
2 doc/src/sgml/ref/copy.sgml
3 PostgreSQL documentation
4 -->
5
6
7 <refentry id="SQL-COPY">
8  <indexterm zone="sql-copy">
9   <primary>COPY</primary>
10  </indexterm>
11
12  <refmeta>
13   <refentrytitle>COPY</refentrytitle>
14   <manvolnum>7</manvolnum>
15   <refmiscinfo>SQL - Language Statements</refmiscinfo>
16  </refmeta>
17
18  <refnamediv>
19   <refname>COPY</refname>
20   <refpurpose>copy data between a file and a table</refpurpose>
21  </refnamediv>
22
23  <refsynopsisdiv>
24 <synopsis>
25 COPY <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ]
26     FROM { '<replaceable class="parameter">filename</replaceable>' | PROGRAM '<replaceable class="parameter">command</replaceable>' | STDIN }
27     [ [ WITH ] ( <replaceable class="parameter">option</replaceable> [, ...] ) ]
28
29 COPY { <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] | ( <replaceable class="parameter">query</replaceable> ) }
30     TO { '<replaceable class="parameter">filename</replaceable>' | PROGRAM '<replaceable class="parameter">command</replaceable>' | STDOUT }
31     [ [ WITH ] ( <replaceable class="parameter">option</replaceable> [, ...] ) ]
32
33 <phrase>where <replaceable class="parameter">option</replaceable> can be one of:</phrase>
34
35     FORMAT <replaceable class="parameter">format_name</replaceable>
36     OIDS [ <replaceable class="parameter">boolean</replaceable> ]
37     FREEZE [ <replaceable class="parameter">boolean</replaceable> ]
38     DELIMITER '<replaceable class="parameter">delimiter_character</replaceable>'
39     NULL '<replaceable class="parameter">null_string</replaceable>'
40     HEADER [ <replaceable class="parameter">boolean</replaceable> ]
41     QUOTE '<replaceable class="parameter">quote_character</replaceable>'
42     ESCAPE '<replaceable class="parameter">escape_character</replaceable>'
43     FORCE_QUOTE { ( <replaceable class="parameter">column_name</replaceable> [, ...] ) | * }
44     FORCE_NOT_NULL ( <replaceable class="parameter">column_name</replaceable> [, ...] )
45     FORCE_NULL ( <replaceable class="parameter">column_name</replaceable> [, ...] )
46     ENCODING '<replaceable class="parameter">encoding_name</replaceable>'
47 </synopsis>
48  </refsynopsisdiv>
49
50  <refsect1>
51   <title>Description</title>
52
53   <para>
54    <command>COPY</command> moves data between
55    <productname>PostgreSQL</productname> tables and standard file-system
56    files. <command>COPY TO</command> copies the contents of a table
57    <emphasis>to</> a file, while <command>COPY FROM</command> copies
58    data <emphasis>from</> a file to a table (appending the data to
59    whatever is in the table already).  <command>COPY TO</command>
60    can also copy the results of a <command>SELECT</> query.
61   </para>
62
63   <para>
64    If a list of columns is specified, <command>COPY</command> will
65    only copy the data in the specified columns to or from the file.
66    If there are any columns in the table that are not in the column list,
67    <command>COPY FROM</command> will insert the default values for
68    those columns.
69   </para>
70
71   <para>
72    <command>COPY</command> with a file name instructs the
73    <productname>PostgreSQL</productname> server to directly read from
74    or write to a file. The file must be accessible to the server and
75    the name must be specified from the viewpoint of the server. When
76    <literal>PROGRAM</literal> is specified, the server executes the
77    given command, and reads from its standard input, or writes to its
78    standard output. The command must be specified from the viewpoint of the
79    server, and be executable by the <literal>postgres</> user. When
80    <literal>STDIN</literal> or <literal>STDOUT</literal> is
81    specified, data is transmitted via the connection between the
82    client and the server.
83   </para>
84  </refsect1>
85
86  <refsect1>
87   <title>Parameters</title>
88
89   <variablelist>
90    <varlistentry>
91     <term><replaceable class="parameter">table_name</replaceable></term>
92     <listitem>
93      <para>
94       The name (optionally schema-qualified) of an existing table.
95      </para>
96     </listitem>
97    </varlistentry>
98
99    <varlistentry>
100     <term><replaceable class="parameter">column_name</replaceable></term>
101      <listitem>
102      <para>
103       An optional list of columns to be copied.  If no column list is
104       specified, all columns of the table will be copied.
105      </para>
106     </listitem>
107    </varlistentry>
108
109    <varlistentry>
110     <term><replaceable class="parameter">query</replaceable></term>
111     <listitem>
112      <para>
113       A <xref linkend="sql-select"> or
114       <xref linkend="sql-values"> command
115       whose results are to be copied.
116       Note that parentheses are required around the query.
117      </para>
118     </listitem>
119    </varlistentry>
120
121    <varlistentry>
122     <term><replaceable class="parameter">filename</replaceable></term>
123     <listitem>
124      <para>
125       The path name of the input or output file.  An input file name can be
126       an absolute or relative path, but an output file name must be an absolute
127       path.  Windows users might need to use an <literal>E''</> string and
128       double any backslashes used in the path name.
129      </para>
130     </listitem>
131    </varlistentry>
132
133    <varlistentry>
134     <term><literal>PROGRAM</literal></term>
135     <listitem>
136      <para>
137       A command to execute. In <command>COPY FROM</command>, the input is
138       read from standard output of the command, and in <command>COPY TO</>,
139       the output is written to the standard input of the command.
140      </para>
141      <para>
142       Note that the command is invoked by the shell, so if you need to pass
143       any arguments to shell command that come from an untrusted source, you
144       must be careful to strip or escape any special characters that might
145       have a special meaning for the shell. For security reasons, it is best
146       to use a fixed command string, or at least avoid passing any user input
147       in it.
148      </para>
149     </listitem>
150    </varlistentry>
151
152    <varlistentry>
153     <term><literal>STDIN</literal></term>
154     <listitem>
155      <para>
156       Specifies that input comes from the client application.
157      </para>
158     </listitem>
159    </varlistentry>
160
161    <varlistentry>
162     <term><literal>STDOUT</literal></term>
163     <listitem>
164      <para>
165       Specifies that output goes to the client application.
166      </para>
167     </listitem>
168    </varlistentry>
169
170    <varlistentry>
171     <term><replaceable class="parameter">boolean</replaceable></term>
172     <listitem>
173      <para>
174       Specifies whether the selected option should be turned on or off.
175       You can write <literal>TRUE</literal>, <literal>ON</>, or
176       <literal>1</literal> to enable the option, and <literal>FALSE</literal>,
177       <literal>OFF</>, or <literal>0</literal> to disable it.  The
178       <replaceable class="parameter">boolean</replaceable> value can also
179       be omitted, in which case <literal>TRUE</literal> is assumed.
180      </para>
181     </listitem>
182    </varlistentry>
183
184    <varlistentry>
185     <term><literal>FORMAT</literal></term>
186     <listitem>
187      <para>
188       Selects the data format to be read or written:
189       <literal>text</>,
190       <literal>csv</> (Comma Separated Values),
191       or <literal>binary</>.
192       The default is <literal>text</>.
193      </para>
194     </listitem>
195    </varlistentry>
196
197    <varlistentry>
198     <term><literal>OIDS</literal></term>
199     <listitem>
200      <para>
201       Specifies copying the OID for each row.  (An error is raised if
202       <literal>OIDS</literal> is specified for a table that does not
203       have OIDs, or in the case of copying a <replaceable
204       class="parameter">query</replaceable>.)
205      </para>
206     </listitem>
207    </varlistentry>
208
209    <varlistentry>
210     <term><literal>FREEZE</literal></term>
211     <listitem>
212      <para>
213       Requests copying the data with rows already frozen, just as they
214       would be after running the <command>VACUUM FREEZE</> command.
215       This is intended as a performance option for initial data loading.
216       Rows will be frozen only if the table being loaded has been created
217       or truncated in the current subtransaction, there are no cursors
218       open and there are no older snapshots held by this transaction.
219      </para>
220      <para>
221       Note that all other sessions will immediately be able to see the data
222       once it has been successfully loaded. This violates the normal rules
223       of MVCC visibility and users specifying should be aware of the
224       potential problems this might cause.
225      </para>
226     </listitem>
227    </varlistentry>
228
229    <varlistentry>
230     <term><literal>DELIMITER</literal></term>
231     <listitem>
232      <para>
233       Specifies the character that separates columns within each row
234       (line) of the file.  The default is a tab character in text format,
235       a comma in <literal>CSV</> format.
236       This must be a single one-byte character.
237       This option is not allowed when using <literal>binary</> format.
238      </para>
239     </listitem>
240    </varlistentry>
241
242    <varlistentry>
243     <term><literal>NULL</literal></term>
244     <listitem>
245      <para>
246       Specifies the string that represents a null value. The default is
247       <literal>\N</literal> (backslash-N) in text format, and an unquoted empty
248       string in <literal>CSV</> format. You might prefer an
249       empty string even in text format for cases where you don't want to
250       distinguish nulls from empty strings.
251       This option is not allowed when using <literal>binary</> format.
252      </para>
253
254      <note>
255       <para>
256        When using <command>COPY FROM</command>, any data item that matches
257        this string will be stored as a null value, so you should make
258        sure that you use the same string as you used with
259        <command>COPY TO</command>.
260       </para>
261      </note>
262
263     </listitem>
264    </varlistentry>
265
266    <varlistentry>
267     <term><literal>HEADER</literal></term>
268     <listitem>
269      <para>
270       Specifies that the file contains a header line with the names of each
271       column in the file.  On output, the first line contains the column
272       names from the table, and on input, the first line is ignored.
273       This option is allowed only when using <literal>CSV</> format.
274      </para>
275     </listitem>
276    </varlistentry>
277
278    <varlistentry>
279     <term><literal>QUOTE</literal></term>
280     <listitem>
281      <para>
282       Specifies the quoting character to be used when a data value is quoted.
283       The default is double-quote.
284       This must be a single one-byte character.
285       This option is allowed only when using <literal>CSV</> format.
286      </para>
287     </listitem>
288    </varlistentry>
289
290    <varlistentry>
291     <term><literal>ESCAPE</literal></term>
292     <listitem>
293      <para>
294       Specifies the character that should appear before a
295       data character that matches the <literal>QUOTE</> value.
296       The default is the same as the <literal>QUOTE</> value (so that
297       the quoting character is doubled if it appears in the data).
298       This must be a single one-byte character.
299       This option is allowed only when using <literal>CSV</> format.
300      </para>
301     </listitem>
302    </varlistentry>
303
304    <varlistentry>
305     <term><literal>FORCE_QUOTE</></term>
306     <listitem>
307      <para>
308       Forces quoting to be
309       used for all non-<literal>NULL</> values in each specified column.
310       <literal>NULL</> output is never quoted. If <literal>*</> is specified,
311       non-<literal>NULL</> values will be quoted in all columns.
312       This option is allowed only in <command>COPY TO</>, and only when
313       using <literal>CSV</> format.
314      </para>
315     </listitem>
316    </varlistentry>
317
318    <varlistentry>
319     <term><literal>FORCE_NOT_NULL</></term>
320     <listitem>
321      <para>
322       Do not match the specified columns' values against the null string.
323       In the default case where the null string is empty, this means that
324       empty values will be read as zero-length strings rather than nulls,
325       even when they are not quoted.
326       This option is allowed only in <command>COPY FROM</>, and only when
327       using <literal>CSV</> format.
328      </para>
329     </listitem>
330    </varlistentry>
331
332    <varlistentry>
333     <term><literal>FORCE_NULL</></term>
334     <listitem>
335      <para>
336       Match the specified columns' values against the null string, even
337       if it has been quoted, and if a match is found set the value to
338       <literal>NULL</>. In the default case where the null string is empty,
339       this converts a quoted empty string into NULL.
340       This option is allowed only in <command>COPY FROM</>, and only when
341       using <literal>CSV</> format.
342      </para>
343     </listitem>
344    </varlistentry>
345
346    <varlistentry>
347     <term><literal>ENCODING</></term>
348     <listitem>
349      <para>
350       Specifies that the file is encoded in the <replaceable
351       class="parameter">encoding_name</replaceable>.  If this option is
352       omitted, the current client encoding is used. See the Notes below
353       for more details.
354      </para>
355     </listitem>
356    </varlistentry>
357
358   </variablelist>
359  </refsect1>
360
361  <refsect1>
362   <title>Outputs</title>
363
364   <para>
365    On successful completion, a <command>COPY</> command returns a command
366    tag of the form
367 <screen>
368 COPY <replaceable class="parameter">count</replaceable>
369 </screen>
370    The <replaceable class="parameter">count</replaceable> is the number
371    of rows copied.
372   </para>
373
374   <note>
375    <para>
376     <application>psql</> will print this command tag only if the command
377     was not <literal>COPY ... TO STDOUT</>, or the
378     equivalent <application>psql</> meta-command
379     <literal>\copy ... to stdout</>.  This is to prevent confusing the
380     command tag with the data that was just printed.
381    </para>
382   </note>
383  </refsect1>
384
385  <refsect1>
386   <title>Notes</title>
387
388    <para>
389     <command>COPY</command> can only be used with plain tables, not
390     with views.  However, you can write <literal>COPY (SELECT * FROM
391     <replaceable class="parameter">viewname</replaceable>) TO ...</literal>.
392    </para>
393
394    <para>
395     <command>COPY</command> only deals with the specific table named;
396     it does not copy data to or from child tables.  Thus for example
397     <literal>COPY <replaceable class="parameter">table</> TO</literal>
398     shows the same data as <literal>SELECT * FROM ONLY <replaceable
399     class="parameter">table</></literal>.  But <literal>COPY
400     (SELECT * FROM <replaceable class="parameter">table</>) TO ...</literal>
401     can be used to dump all of the data in an inheritance hierarchy.
402    </para>
403
404    <para>
405     You must have select privilege on the table
406     whose values are read by <command>COPY TO</command>, and
407     insert privilege on the table into which values
408     are inserted by <command>COPY FROM</command>.  It is sufficient
409     to have column privileges on the column(s) listed in the command.
410    </para>
411
412    <para>
413     Files named in a <command>COPY</command> command are read or written
414     directly by the server, not by the client application. Therefore,
415     they must reside on or be accessible to the database server machine,
416     not the client. They must be accessible to and readable or writable
417     by the <productname>PostgreSQL</productname> user (the user ID the
418     server runs as), not the client. Similarly,
419     the command specified with <literal>PROGRAM</literal> is executed directly
420     by the server, not by the client application, must be executable by the
421     <productname>PostgreSQL</productname> user.
422     <command>COPY</command> naming a file or command is only allowed to
423     database superusers, since it allows reading or writing any file that the
424     server has privileges to access.
425    </para>
426
427    <para>
428     Do not confuse <command>COPY</command> with the
429     <application>psql</application> instruction
430     <command><link linkend="APP-PSQL-meta-commands-copy">\copy</link></command>. <command>\copy</command> invokes
431     <command>COPY FROM STDIN</command> or <command>COPY TO
432     STDOUT</command>, and then fetches/stores the data in a file
433     accessible to the <application>psql</application> client. Thus,
434     file accessibility and access rights depend on the client rather
435     than the server when <command>\copy</command> is used.
436    </para>
437
438    <para>
439     It is recommended that the file name used in <command>COPY</command>
440     always be specified as an absolute path. This is enforced by the
441     server in the case of <command>COPY TO</command>, but for
442     <command>COPY FROM</command> you do have the option of reading from
443     a file specified by a relative path. The path will be interpreted
444     relative to the working directory of the server process (normally
445     the cluster's data directory), not the client's working directory.
446    </para>
447
448    <para>
449     Executing a command with <literal>PROGRAM</literal> might be restricted
450     by the operating system's access control mechanisms, such as SELinux.
451    </para>
452
453    <para>
454     <command>COPY FROM</command> will invoke any triggers and check
455     constraints on the destination table. However, it will not invoke rules.
456    </para>
457
458    <para>
459     <command>COPY</command> input and output is affected by
460     <varname>DateStyle</varname>. To ensure portability to other
461     <productname>PostgreSQL</productname> installations that might use
462     non-default <varname>DateStyle</varname> settings,
463     <varname>DateStyle</varname> should be set to <literal>ISO</> before
464     using <command>COPY TO</>.  It is also a good idea to avoid dumping
465     data with <varname>IntervalStyle</varname> set to
466     <literal>sql_standard</>, because negative interval values might be
467     misinterpreted by a server that has a different setting for
468     <varname>IntervalStyle</varname>.
469    </para>
470
471    <para>
472     Input data is interpreted according to <literal>ENCODING</literal>
473     option or the current client encoding, and output data is encoded
474     in <literal>ENCODING</literal> or the current client encoding, even
475     if the data does not pass through the client but is read from or
476     written to a file directly by the server.
477    </para>
478
479    <para>
480     <command>COPY</command> stops operation at the first error. This
481     should not lead to problems in the event of a <command>COPY
482     TO</command>, but the target table will already have received
483     earlier rows in a <command>COPY FROM</command>. These rows will not
484     be visible or accessible, but they still occupy disk space. This might
485     amount to a considerable amount of wasted disk space if the failure
486     happened well into a large copy operation. You might wish to invoke
487     <command>VACUUM</command> to recover the wasted space.
488    </para>
489
490  </refsect1>
491
492  <refsect1>
493   <title>File Formats</title>
494
495   <refsect2>
496    <title>Text Format</title>
497
498    <para>
499     When the <literal>text</> format is used,
500     the data read or written is a text file with one line per table row.
501     Columns in a row are separated by the delimiter character.
502     The column values themselves are strings generated by the
503     output function, or acceptable to the input function, of each
504     attribute's data type.  The specified null string is used in
505     place of columns that are null.
506     <command>COPY FROM</command> will raise an error if any line of the
507     input file contains more or fewer columns than are expected.
508     If <literal>OIDS</literal> is specified, the OID is read or written as the first column,
509     preceding the user data columns.
510    </para>
511
512    <para>
513     End of data can be represented by a single line containing just
514     backslash-period (<literal>\.</>).  An end-of-data marker is
515     not necessary when reading from a file, since the end of file
516     serves perfectly well; it is needed only when copying data to or from
517     client applications using pre-3.0 client protocol.
518    </para>
519
520    <para>
521     Backslash characters (<literal>\</>) can be used in the
522     <command>COPY</command> data to quote data characters that might
523     otherwise be taken as row or column delimiters. In particular, the
524     following characters <emphasis>must</> be preceded by a backslash if
525     they appear as part of a column value: backslash itself,
526     newline, carriage return, and the current delimiter character.
527    </para>
528
529    <para>
530     The specified null string is sent by <command>COPY TO</command> without
531     adding any backslashes; conversely, <command>COPY FROM</command> matches
532     the input against the null string before removing backslashes.  Therefore,
533     a null string such as <literal>\N</literal> cannot be confused with
534     the actual data value <literal>\N</literal> (which would be represented
535     as <literal>\\N</literal>).
536    </para>
537
538    <para>
539     The following special backslash sequences are recognized by
540     <command>COPY FROM</command>:
541
542    <informaltable>
543     <tgroup cols="2">
544      <thead>
545       <row>
546        <entry>Sequence</entry>
547        <entry>Represents</entry>
548       </row>
549      </thead>
550
551      <tbody>
552       <row>
553        <entry><literal>\b</></entry>
554        <entry>Backspace (ASCII 8)</entry>
555       </row>
556       <row>
557        <entry><literal>\f</></entry>
558        <entry>Form feed (ASCII 12)</entry>
559       </row>
560       <row>
561        <entry><literal>\n</></entry>
562        <entry>Newline (ASCII 10)</entry>
563       </row>
564       <row>
565        <entry><literal>\r</></entry>
566        <entry>Carriage return (ASCII 13)</entry>
567       </row>
568       <row>
569        <entry><literal>\t</></entry>
570        <entry>Tab (ASCII 9)</entry>
571       </row>
572       <row>
573        <entry><literal>\v</></entry>
574        <entry>Vertical tab (ASCII 11)</entry>
575       </row>
576       <row>
577        <entry><literal>\</><replaceable>digits</></entry>
578        <entry>Backslash followed by one to three octal digits specifies
579        the character with that numeric code</entry>
580       </row>
581       <row>
582        <entry><literal>\x</><replaceable>digits</></entry>
583        <entry>Backslash <literal>x</> followed by one or two hex digits specifies
584        the character with that numeric code</entry>
585       </row>
586      </tbody>
587     </tgroup>
588    </informaltable>
589
590     Presently, <command>COPY TO</command> will never emit an octal or
591     hex-digits backslash sequence, but it does use the other sequences
592     listed above for those control characters.
593    </para>
594
595    <para>
596     Any other backslashed character that is not mentioned in the above table
597     will be taken to represent itself.  However, beware of adding backslashes
598     unnecessarily, since that might accidentally produce a string matching the
599     end-of-data marker (<literal>\.</>) or the null string (<literal>\N</> by
600     default).  These strings will be recognized before any other backslash
601     processing is done.
602    </para>
603
604    <para>
605     It is strongly recommended that applications generating <command>COPY</command> data convert
606     data newlines and carriage returns to the <literal>\n</> and
607     <literal>\r</> sequences respectively.  At present it is
608     possible to represent a data carriage return by a backslash and carriage
609     return, and to represent a data newline by a backslash and newline.
610     However, these representations might not be accepted in future releases.
611     They are also highly vulnerable to corruption if the <command>COPY</command> file is
612     transferred across different machines (for example, from Unix to Windows
613     or vice versa).
614    </para>
615
616    <para>
617     <command>COPY TO</command> will terminate each row with a Unix-style
618     newline (<quote><literal>\n</></>).  Servers running on Microsoft Windows instead
619     output carriage return/newline (<quote><literal>\r\n</></>), but only for
620     <command>COPY</> to a server file; for consistency across platforms,
621     <command>COPY TO STDOUT</> always sends <quote><literal>\n</></>
622     regardless of server platform.
623     <command>COPY FROM</command> can handle lines ending with newlines,
624     carriage returns, or carriage return/newlines.  To reduce the risk of
625     error due to un-backslashed newlines or carriage returns that were
626     meant as data, <command>COPY FROM</command> will complain if the line
627     endings in the input are not all alike.
628    </para>
629   </refsect2>
630
631   <refsect2>
632    <title>CSV Format</title>
633
634    <para>
635     This format option is used for importing and exporting the Comma
636     Separated Value (<literal>CSV</>) file format used by many other
637     programs, such as spreadsheets. Instead of the escaping rules used by
638     <productname>PostgreSQL</productname>'s standard text format, it
639     produces and recognizes the common CSV escaping mechanism.
640    </para>
641
642    <para>
643     The values in each record are separated by the <literal>DELIMITER</>
644     character. If the value contains the delimiter character, the
645     <literal>QUOTE</> character, the <literal>NULL</> string, a carriage
646     return, or line feed character, then the whole value is prefixed and
647     suffixed by the <literal>QUOTE</> character, and any occurrence
648     within the value of a <literal>QUOTE</> character or the
649     <literal>ESCAPE</> character is preceded by the escape character.
650     You can also use <literal>FORCE_QUOTE</> to force quotes when outputting
651     non-<literal>NULL</> values in specific columns.
652    </para>
653
654    <para>
655     The <literal>CSV</> format has no standard way to distinguish a
656     <literal>NULL</> value from an empty string.
657     <productname>PostgreSQL</>'s <command>COPY</> handles this by quoting.
658     A <literal>NULL</> is output as the <literal>NULL</> parameter string
659     and is not quoted, while a non-<literal>NULL</> value matching the
660     <literal>NULL</> parameter string is quoted.  For example, with the
661     default settings, a <literal>NULL</> is written as an unquoted empty
662     string, while an empty string data value is written with double quotes
663     (<literal>""</>). Reading values follows similar rules. You can
664     use <literal>FORCE_NOT_NULL</> to prevent <literal>NULL</> input
665     comparisons for specific columns. You can also use
666     <literal>FORCE_NULL</> to convert quoted null string data values to
667     <literal>NULL</>.
668    </para>
669
670    <para>
671     Because backslash is not a special character in the <literal>CSV</>
672     format, <literal>\.</>, the end-of-data marker, could also appear
673     as a data value.  To avoid any misinterpretation, a <literal>\.</>
674     data value appearing as a lone entry on a line is automatically
675     quoted on output, and on input, if quoted, is not interpreted as the
676     end-of-data marker.  If you are loading a file created by another
677     application that has a single unquoted column and might have a
678     value of <literal>\.</>, you might need to quote that value in the
679     input file.
680    </para>
681
682    <note>
683     <para>
684      In <literal>CSV</> format, all characters are significant. A quoted value
685      surrounded by white space, or any characters other than
686      <literal>DELIMITER</>, will include those characters. This can cause
687      errors if you import data from a system that pads <literal>CSV</>
688      lines with white space out to some fixed width. If such a situation
689      arises you might need to preprocess the <literal>CSV</> file to remove
690      the trailing white space, before importing the data into
691      <productname>PostgreSQL</>.
692     </para>
693    </note>
694
695    <note>
696     <para>
697      CSV format will both recognize and produce CSV files with quoted
698      values containing embedded carriage returns and line feeds. Thus
699      the files are not strictly one line per table row like text-format
700      files.
701     </para>
702    </note>
703
704    <note>
705     <para>
706      Many programs produce strange and occasionally perverse CSV files,
707      so the file format is more a convention than a standard. Thus you
708      might encounter some files that cannot be imported using this
709      mechanism, and <command>COPY</> might produce files that other
710      programs cannot process.
711     </para>
712    </note>
713
714   </refsect2>
715
716   <refsect2>
717    <title>Binary Format</title>
718
719    <para>
720     The <literal>binary</literal> format option causes all data to be
721     stored/read as binary format rather than as text.  It is
722     somewhat faster than the text and <literal>CSV</> formats,
723     but a binary-format file is less portable across machine architectures and
724     <productname>PostgreSQL</productname> versions.
725     Also, the binary format is very data type specific; for example
726     it will not work to output binary data from a <type>smallint</> column
727     and read it into an <type>integer</> column, even though that would work
728     fine in text format.
729    </para>
730
731    <para>
732     The <literal>binary</> file format consists
733     of a file header, zero or more tuples containing the row data, and
734     a file trailer.  Headers and data are in network byte order.
735    </para>
736
737    <note>
738     <para>
739      <productname>PostgreSQL</productname> releases before 7.4 used a
740      different binary file format.
741     </para>
742    </note>
743
744    <refsect3>
745     <title>File Header</title>
746
747     <para>
748      The file header consists of 15 bytes of fixed fields, followed
749      by a variable-length header extension area.  The fixed fields are:
750
751     <variablelist>
752      <varlistentry>
753       <term>Signature</term>
754       <listitem>
755        <para>
756 11-byte sequence <literal>PGCOPY\n\377\r\n\0</> &mdash; note that the zero byte
757 is a required part of the signature.  (The signature is designed to allow
758 easy identification of files that have been munged by a non-8-bit-clean
759 transfer.  This signature will be changed by end-of-line-translation
760 filters, dropped zero bytes, dropped high bits, or parity changes.)
761        </para>
762       </listitem>
763      </varlistentry>
764
765      <varlistentry>
766       <term>Flags field</term>
767       <listitem>
768        <para>
769 32-bit integer bit mask to denote important aspects of the file format. Bits
770 are numbered from 0 (<acronym>LSB</>) to 31 (<acronym>MSB</>).  Note that
771 this field is stored in network byte order (most significant byte first),
772 as are all the integer fields used in the file format.  Bits
773 16-31 are reserved to denote critical file format issues; a reader
774 should abort if it finds an unexpected bit set in this range. Bits 0-15
775 are reserved to signal backwards-compatible format issues; a reader
776 should simply ignore any unexpected bits set in this range. Currently
777 only one flag bit is defined, and the rest must be zero:
778         <variablelist>
779          <varlistentry>
780           <term>Bit 16</term>
781           <listitem>
782            <para>
783             if 1, OIDs are included in the data; if 0, not
784            </para>
785           </listitem>
786          </varlistentry>
787         </variablelist></para>
788       </listitem>
789      </varlistentry>
790
791      <varlistentry>
792       <term>Header extension area length</term>
793       <listitem>
794        <para>
795 32-bit integer, length in bytes of remainder of header, not including self.
796 Currently, this is zero, and the first tuple follows
797 immediately.  Future changes to the format might allow additional data
798 to be present in the header.  A reader should silently skip over any header
799 extension data it does not know what to do with.
800        </para>
801       </listitem>
802      </varlistentry>
803     </variablelist>
804     </para>
805
806     <para>
807 The header extension area is envisioned to contain a sequence of
808 self-identifying chunks.  The flags field is not intended to tell readers
809 what is in the extension area.  Specific design of header extension contents
810 is left for a later release.
811     </para>
812
813     <para>
814      This design allows for both backwards-compatible header additions (add
815      header extension chunks, or set low-order flag bits) and
816      non-backwards-compatible changes (set high-order flag bits to signal such
817      changes, and add supporting data to the extension area if needed).
818     </para>
819    </refsect3>
820
821    <refsect3>
822     <title>Tuples</title>
823     <para>
824 Each tuple begins with a 16-bit integer count of the number of fields in the
825 tuple.  (Presently, all tuples in a table will have the same count, but that
826 might not always be true.)  Then, repeated for each field in the tuple, there
827 is a 32-bit length word followed by that many bytes of field data.  (The
828 length word does not include itself, and can be zero.)  As a special case,
829 -1 indicates a NULL field value.  No value bytes follow in the NULL case.
830     </para>
831
832     <para>
833 There is no alignment padding or any other extra data between fields.
834     </para>
835
836     <para>
837 Presently, all data values in a binary-format file are
838 assumed to be in binary format (format code one).  It is anticipated that a
839 future extension might add a header field that allows per-column format codes
840 to be specified.
841     </para>
842
843     <para>
844 To determine the appropriate binary format for the actual tuple data you
845 should consult the <productname>PostgreSQL</productname> source, in
846 particular the <function>*send</> and <function>*recv</> functions for
847 each column's data type (typically these functions are found in the
848 <filename>src/backend/utils/adt/</filename> directory of the source
849 distribution).
850     </para>
851
852     <para>
853 If OIDs are included in the file, the OID field immediately follows the
854 field-count word.  It is a normal field except that it's not included
855 in the field-count.  In particular it has a length word &mdash; this will allow
856 handling of 4-byte vs. 8-byte OIDs without too much pain, and will allow
857 OIDs to be shown as null if that ever proves desirable.
858     </para>
859    </refsect3>
860
861    <refsect3>
862     <title>File Trailer</title>
863
864     <para>
865      The file trailer consists of a 16-bit integer word containing -1.  This
866      is easily distinguished from a tuple's field-count word.
867     </para>
868
869     <para>
870      A reader should report an error if a field-count word is neither -1
871      nor the expected number of columns.  This provides an extra
872      check against somehow getting out of sync with the data.
873     </para>
874    </refsect3>
875   </refsect2>
876  </refsect1>
877
878  <refsect1>
879   <title>Examples</title>
880
881   <para>
882    The following example copies a table to the client
883    using the vertical bar (<literal>|</literal>) as the field delimiter:
884 <programlisting>
885 COPY country TO STDOUT (DELIMITER '|');
886 </programlisting>
887   </para>
888
889   <para>
890    To copy data from a file into the <literal>country</> table:
891 <programlisting>
892 COPY country FROM '/usr1/proj/bray/sql/country_data';
893 </programlisting>
894   </para>
895
896   <para>
897    To copy into a file just the countries whose names start with 'A':
898 <programlisting>
899 COPY (SELECT * FROM country WHERE country_name LIKE 'A%') TO '/usr1/proj/bray/sql/a_list_countries.copy';
900 </programlisting>
901   </para>
902
903   <para>
904    To copy into a compressed file, you can pipe the output through an external
905    compression program:
906 <programlisting>
907 COPY country TO PROGRAM 'gzip > /usr1/proj/bray/sql/country_data.gz';
908 </programlisting>
909   </para>
910
911   <para>
912    Here is a sample of data suitable for copying into a table from
913    <literal>STDIN</literal>:
914 <programlisting>
915 AF      AFGHANISTAN
916 AL      ALBANIA
917 DZ      ALGERIA
918 ZM      ZAMBIA
919 ZW      ZIMBABWE
920 </programlisting>
921    Note that the white space on each line is actually a tab character.
922   </para>
923
924   <para>
925    The following is the same data, output in binary format.
926    The data is shown after filtering through the
927    Unix utility <command>od -c</command>. The table has three columns;
928    the first has type <type>char(2)</type>, the second has type <type>text</type>,
929    and the third has type <type>integer</type>. All the rows have a null value
930    in the third column.
931 <programlisting>
932 0000000   P   G   C   O   P   Y  \n 377  \r  \n  \0  \0  \0  \0  \0  \0
933 0000020  \0  \0  \0  \0 003  \0  \0  \0 002   A   F  \0  \0  \0 013   A
934 0000040   F   G   H   A   N   I   S   T   A   N 377 377 377 377  \0 003
935 0000060  \0  \0  \0 002   A   L  \0  \0  \0 007   A   L   B   A   N   I
936 0000100   A 377 377 377 377  \0 003  \0  \0  \0 002   D   Z  \0  \0  \0
937 0000120 007   A   L   G   E   R   I   A 377 377 377 377  \0 003  \0  \0
938 0000140  \0 002   Z   M  \0  \0  \0 006   Z   A   M   B   I   A 377 377
939 0000160 377 377  \0 003  \0  \0  \0 002   Z   W  \0  \0  \0  \b   Z   I
940 0000200   M   B   A   B   W   E 377 377 377 377 377 377
941 </programlisting></para>
942  </refsect1>
943
944  <refsect1>
945   <title>Compatibility</title>
946
947   <para>
948    There is no <command>COPY</command> statement in the SQL standard.
949   </para>
950
951   <para>
952    The following syntax was used before <productname>PostgreSQL</>
953    version 9.0 and is still supported:
954
955 <synopsis>
956 COPY <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ]
957     FROM { '<replaceable class="parameter">filename</replaceable>' | STDIN }
958     [ [ WITH ]
959           [ BINARY ]
960           [ OIDS ]
961           [ DELIMITER [ AS ] '<replaceable class="parameter">delimiter</replaceable>' ]
962           [ NULL [ AS ] '<replaceable class="parameter">null string</replaceable>' ]
963           [ CSV [ HEADER ]
964                 [ QUOTE [ AS ] '<replaceable class="parameter">quote</replaceable>' ]
965                 [ ESCAPE [ AS ] '<replaceable class="parameter">escape</replaceable>' ]
966                 [ FORCE NOT NULL <replaceable class="parameter">column_name</replaceable> [, ...] ] ] ]
967
968 COPY { <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] | ( <replaceable class="parameter">query</replaceable> ) }
969     TO { '<replaceable class="parameter">filename</replaceable>' | STDOUT }
970     [ [ WITH ]
971           [ BINARY ]
972           [ OIDS ]
973           [ DELIMITER [ AS ] '<replaceable class="parameter">delimiter</replaceable>' ]
974           [ NULL [ AS ] '<replaceable class="parameter">null string</replaceable>' ]
975           [ CSV [ HEADER ]
976                 [ QUOTE [ AS ] '<replaceable class="parameter">quote</replaceable>' ]
977                 [ ESCAPE [ AS ] '<replaceable class="parameter">escape</replaceable>' ]
978                 [ FORCE QUOTE { <replaceable class="parameter">column_name</replaceable> [, ...] | * } ] ] ]
979 </synopsis>
980
981    Note that in this syntax, <literal>BINARY</> and <literal>CSV</> are
982    treated as independent keywords, not as arguments of a <literal>FORMAT</>
983    option.
984   </para>
985
986   <para>
987    The following syntax was used before <productname>PostgreSQL</>
988    version 7.3 and is still supported:
989
990 <synopsis>
991 COPY [ BINARY ] <replaceable class="parameter">table_name</replaceable> [ WITH OIDS ]
992     FROM { '<replaceable class="parameter">filename</replaceable>' | STDIN }
993     [ [USING] DELIMITERS '<replaceable class="parameter">delimiter</replaceable>' ]
994     [ WITH NULL AS '<replaceable class="parameter">null string</replaceable>' ]
995
996 COPY [ BINARY ] <replaceable class="parameter">table_name</replaceable> [ WITH OIDS ]
997     TO { '<replaceable class="parameter">filename</replaceable>' | STDOUT }
998     [ [USING] DELIMITERS '<replaceable class="parameter">delimiter</replaceable>' ]
999     [ WITH NULL AS '<replaceable class="parameter">null string</replaceable>' ]
1000 </synopsis></para>
1001  </refsect1>
1002 </refentry>