1COPY() SQL Commands COPY()
2
3
4
6 COPY - copy data between a file and a table
7
8
10 COPY tablename [ ( column [, ...] ) ]
11 FROM { 'filename' | STDIN }
12 [ [ WITH ]
13 [ BINARY ]
14 [ OIDS ]
15 [ DELIMITER [ AS ] 'delimiter' ]
16 [ NULL [ AS ] 'null string' ]
17 [ CSV [ HEADER ]
18 [ QUOTE [ AS ] 'quote' ]
19 [ ESCAPE [ AS ] 'escape' ]
20 [ FORCE NOT NULL column [, ...] ]
21
22 COPY { tablename [ ( column [, ...] ) ] | ( query ) }
23 TO { 'filename' | STDOUT }
24 [ [ WITH ]
25 [ BINARY ]
26 [ HEADER ]
27 [ OIDS ]
28 [ DELIMITER [ AS ] 'delimiter' ]
29 [ NULL [ AS ] 'null string' ]
30 [ CSV [ HEADER ]
31 [ QUOTE [ AS ] 'quote' ]
32 [ ESCAPE [ AS ] 'escape' ]
33 [ FORCE QUOTE column [, ...] ]
34
35
37 COPY moves data between PostgreSQL tables and standard file-system
38 files. COPY TO copies the contents of a table to a file, while COPY
39 FROM copies data from a file to a table (appending the data to whatever
40 is in the table already). COPY TO can also copy the results of a SELECT
41 query.
42
43 If a list of columns is specified, COPY will only copy the data in the
44 specified columns to or from the file. If there are any columns in the
45 table that are not in the column list, COPY FROM will insert the
46 default values for those columns.
47
48 COPY with a file name instructs the PostgreSQL server to directly read
49 from or write to a file. The file must be accessible to the server and
50 the name must be specified from the viewpoint of the server. When STDIN
51 or STDOUT is specified, data is transmitted via the connection between
52 the client and the server.
53
55 tablename
56 The name (optionally schema-qualified) of an existing table.
57
58 column An optional list of columns to be copied. If no column list is
59 specified, all columns of the table will be copied.
60
61 query A SELECT [select(7)] or VALUES [values(7)] command whose results
62 are to be copied. Note that parentheses are required around the
63 query.
64
65 filename
66 The absolute path name of the input or output file. Windows
67 users might need to use an E'' string and double backslashes
68 used as path separators.
69
70 STDIN Specifies that input comes from the client application.
71
72 STDOUT Specifies that output goes to the client application.
73
74 BINARY Causes all data to be stored or read in binary format rather
75 than as text. You cannot specify the DELIMITER, NULL, or CSV
76 options in binary mode.
77
78 OIDS Specifies copying the OID for each row. (An error is raised if
79 OIDS is specified for a table that does not have OIDs, or in the
80 case of copying a query.)
81
82 delimiter
83 The single ASCII character that separates columns within each
84 row (line) of the file. The default is a tab character in text
85 mode, a comma in CSV mode.
86
87 null string
88 The string that represents a null value. The default is \N
89 (backslash-N) in text mode, and a empty value with no quotes in
90 CSV mode. You might prefer an empty string even in text mode for
91 cases where you don't want to distinguish nulls from empty
92 strings.
93
94 Note: When using COPY FROM, any data item that matches this
95 string will be stored as a null value, so you should make sure
96 that you use the same string as you used with COPY TO.
97
98
99 CSV Selects Comma Separated Value (CSV) mode.
100
101 HEADER Specifies the file contains a header line with the names of each
102 column in the file. On output, the first line contains the col‐
103 umn names from the table, and on input, the first line is
104 ignored.
105
106 quote Specifies the ASCII quotation character in CSV mode. The
107 default is double-quote.
108
109 escape Specifies the ASCII character that should appear before a QUOTE
110 data character value in CSV mode. The default is the QUOTE
111 value (usually double-quote).
112
113 FORCE QUOTE
114 In CSV COPY TO mode, forces quoting to be used for all non-NULL
115 values in each specified column. NULL output is never quoted.
116
117 FORCE NOT NULL
118 In CSV COPY FROM mode, process each specified column as though
119 it were quoted and hence not a NULL value. For the default null
120 string in CSV mode (''), this causes missing values to be input
121 as zero-length strings.
122
124 On successful completion, a COPY command returns a command tag of the
125 form
126
127 COPY count
128
129 The count is the number of rows copied.
130
132 COPY can only be used with plain tables, not with views. However, you
133 can write COPY (SELECT * FROM viewname) TO ....
134
135 The BINARY key word causes all data to be stored/read as binary format
136 rather than as text. It is somewhat faster than the normal text mode,
137 but a binary-format file is less portable across machine architectures
138 and PostgreSQL versions.
139
140 You must have select privilege on the table whose values are read by
141 COPY TO, and insert privilege on the table into which values are
142 inserted by COPY FROM.
143
144 Files named in a COPY command are read or written directly by the
145 server, not by the client application. Therefore, they must reside on
146 or be accessible to the database server machine, not the client. They
147 must be accessible to and readable or writable by the PostgreSQL user
148 (the user ID the server runs as), not the client. COPY naming a file is
149 only allowed to database superusers, since it allows reading or writing
150 any file that the server has privileges to access.
151
152 Do not confuse COPY with the psql instruction \copy. \copy invokes COPY
153 FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a
154 file accessible to the psql client. Thus, file accessibility and access
155 rights depend on the client rather than the server when \copy is used.
156
157 It is recommended that the file name used in COPY always be specified
158 as an absolute path. This is enforced by the server in the case of COPY
159 TO, but for COPY FROM you do have the option of reading from a file
160 specified by a relative path. The path will be interpreted relative to
161 the working directory of the server process (normally the cluster's
162 data directory), not the client's working directory.
163
164 COPY FROM will invoke any triggers and check constraints on the desti‐
165 nation table. However, it will not invoke rules.
166
167 COPY input and output is affected by DateStyle. To ensure portability
168 to other PostgreSQL installations that might use non-default DateStyle
169 settings, DateStyle should be set to ISO before using COPY TO.
170
171 COPY stops operation at the first error. This should not lead to prob‐
172 lems in the event of a COPY TO, but the target table will already have
173 received earlier rows in a COPY FROM. These rows will not be visible or
174 accessible, but they still occupy disk space. This may amount to a con‐
175 siderable amount of wasted disk space if the failure happened well into
176 a large copy operation. You may wish to invoke VACUUM to recover the
177 wasted space.
178
180 TEXT FORMAT
181 When COPY is used without the BINARY or CSV options, the data read or
182 written is a text file with one line per table row. Columns in a row
183 are separated by the delimiter character. The column values themselves
184 are strings generated by the output function, or acceptable to the
185 input function, of each attribute's data type. The specified null
186 string is used in place of columns that are null. COPY FROM will raise
187 an error if any line of the input file contains more or fewer columns
188 than are expected. If OIDS is specified, the OID is read or written as
189 the first column, preceding the user data columns.
190
191 End of data can be represented by a single line containing just back‐
192 slash-period (\.). An end-of-data marker is not necessary when reading
193 from a file, since the end of file serves perfectly well; it is needed
194 only when copying data to or from client applications using pre-3.0
195 client protocol.
196
197 Backslash characters (\) may be used in the COPY data to quote data
198 characters that might otherwise be taken as row or column delimiters.
199 In particular, the following characters must be preceded by a backslash
200 if they appear as part of a column value: backslash itself, newline,
201 carriage return, and the current delimiter character.
202
203 The specified null string is sent by COPY TO without adding any back‐
204 slashes; conversely, COPY FROM matches the input against the null
205 string before removing backslashes. Therefore, a null string such as \N
206 cannot be confused with the actual data value \N (which would be repre‐
207 sented as \\N).
208
209 The following special backslash sequences are recognized by COPY FROM:
210 SequenceRepresents\bBackspace (ASCII 8)\fForm feed (ASCII 12)\nNewline
211 (ASCII 10)\rCarriage return (ASCII 13)\tTab (ASCII 9)\vVertical tab
212 (ASCII 11)\digitsBackslash followed by one to three octal digits speci‐
213 fies the character with that numeric code\xdigitsBackslash x followed
214 by one or two hex digits specifies the character with that numeric code
215 Presently, COPY TO will never emit an octal or hex-digits backslash
216 sequence, but it does use the other sequences listed above for those
217 control characters.
218
219 Any other backslashed character that is not mentioned in the above ta‐
220 ble will be taken to represent itself. However, beware of adding back‐
221 slashes unnecessarily, since that might accidentally produce a string
222 matching the end-of-data marker (\.) or the null string (\N by
223 default). These strings will be recognized before any other backslash
224 processing is done.
225
226 It is strongly recommended that applications generating COPY data con‐
227 vert data newlines and carriage returns to the \n and \r sequences
228 respectively. At present it is possible to represent a data carriage
229 return by a backslash and carriage return, and to represent a data new‐
230 line by a backslash and newline. However, these representations might
231 not be accepted in future releases. They are also highly vulnerable to
232 corruption if the COPY file is transferred across different machines
233 (for example, from Unix to Windows or vice versa).
234
235 COPY TO will terminate each row with a Unix-style newline (``\n'').
236 Servers running on Microsoft Windows instead output carriage
237 return/newline (``\r\n''), but only for COPY to a server file; for con‐
238 sistency across platforms, COPY TO STDOUT always sends ``\n'' regard‐
239 less of server platform. COPY FROM can handle lines ending with new‐
240 lines, carriage returns, or carriage return/newlines. To reduce the
241 risk of error due to un-backslashed newlines or carriage returns that
242 were meant as data, COPY FROM will complain if the line endings in the
243 input are not all alike.
244
245 CSV FORMAT
246 This format is used for importing and exporting the Comma Separated
247 Value (CSV) file format used by many other programs, such as spread‐
248 sheets. Instead of the escaping used by PostgreSQL's standard text
249 mode, it produces and recognizes the common CSV escaping mechanism.
250
251 The values in each record are separated by the DELIMITER character. If
252 the value contains the delimiter character, the QUOTE character, the
253 NULL string, a carriage return, or line feed character, then the whole
254 value is prefixed and suffixed by the QUOTE character, and any occur‐
255 rence within the value of a QUOTE character or the ESCAPE character is
256 preceded by the escape character. You can also use FORCE QUOTE to
257 force quotes when outputting non-NULL values in specific columns.
258
259 The CSV format has no standard way to distinguish a NULL value from an
260 empty string. PostgreSQL's COPY handles this by quoting. A NULL is
261 output as the NULL string and is not quoted, while a data value match‐
262 ing the NULL string is quoted. Therefore, using the default settings, a
263 NULL is written as an unquoted empty string, while an empty string is
264 written with double quotes (""). Reading values follows similar rules.
265 You can use FORCE NOT NULL to prevent NULL input comparisons for spe‐
266 cific columns.
267
268 Because backslash is not a special character in the CSV format, \., the
269 end-of-data marker, could also appear as a data value. To avoid any
270 misinterpretation, a \. data value appearing as a lone entry on a line
271 is automatically quoted on output, and on input, if quoted, is not
272 interpreted as the end-of-data marker. If you are loading a file cre‐
273 ated by another application that has a single unquoted column and might
274 have a value of \., you might need to quote that value in the input
275 file.
276
277 Note: In CSV mode, all characters are significant. A quoted
278 value surrounded by white space, or any characters other than
279 DELIMITER, will include those characters. This can cause errors
280 if you import data from a system that pads CSV lines with white
281 space out to some fixed width. If such a situation arises you
282 might need to preprocess the CSV file to remove the trailing
283 white space, before importing the data into PostgreSQL.
284
285
286 Note: CSV mode will both recognize and produce CSV files with
287 quoted values containing embedded carriage returns and line
288 feeds. Thus the files are not strictly one line per table row
289 like text-mode files.
290
291
292 Note: Many programs produce strange and occasionally perverse
293 CSV files, so the file format is more a convention than a stan‐
294 dard. Thus you might encounter some files that cannot be
295 imported using this mechanism, and COPY might produce files that
296 other programs cannot process.
297
298
299 BINARY FORMAT
300 The file format used for COPY BINARY changed in PostgreSQL 7.4. The new
301 format consists of a file header, zero or more tuples containing the
302 row data, and a file trailer. Headers and data are now in network byte
303 order.
304
305 FILE HEADER
306 The file header consists of 15 bytes of fixed fields, followed by a
307 variable-length header extension area. The fixed fields are:
308
309 Signature
310 11-byte sequence PGCOPY\n\377\r\n\0 — note that the zero byte is
311 a required part of the signature. (The signature is designed to
312 allow easy identification of files that have been munged by a
313 non-8-bit-clean transfer. This signature will be changed by end-
314 of-line-translation filters, dropped zero bytes, dropped high
315 bits, or parity changes.)
316
317 Flags field
318 32-bit integer bit mask to denote important aspects of the file
319 format. Bits are numbered from 0 (LSB) to 31 (MSB). Note that
320 this field is stored in network byte order (most significant
321 byte first), as are all the integer fields used in the file for‐
322 mat. Bits 16-31 are reserved to denote critical file format
323 issues; a reader should abort if it finds an unexpected bit set
324 in this range. Bits 0-15 are reserved to signal backwards-com‐
325 patible format issues; a reader should simply ignore any unex‐
326 pected bits set in this range. Currently only one flag bit is
327 defined, and the rest must be zero:
328
329 Bit 16 if 1, OIDs are included in the data; if 0, not
330
331 Header extension area length
332 32-bit integer, length in bytes of remainder of header, not
333 including self. Currently, this is zero, and the first tuple
334 follows immediately. Future changes to the format might allow
335 additional data to be present in the header. A reader should
336 silently skip over any header extension data it does not know
337 what to do with.
338
339 The header extension area is envisioned to contain a sequence of self-
340 identifying chunks. The flags field is not intended to tell readers
341 what is in the extension area. Specific design of header extension con‐
342 tents is left for a later release.
343
344 This design allows for both backwards-compatible header additions (add
345 header extension chunks, or set low-order flag bits) and non-backwards-
346 compatible changes (set high-order flag bits to signal such changes,
347 and add supporting data to the extension area if needed).
348
349 TUPLES
350 Each tuple begins with a 16-bit integer count of the number of fields
351 in the tuple. (Presently, all tuples in a table will have the same
352 count, but that might not always be true.) Then, repeated for each
353 field in the tuple, there is a 32-bit length word followed by that many
354 bytes of field data. (The length word does not include itself, and can
355 be zero.) As a special case, -1 indicates a NULL field value. No value
356 bytes follow in the NULL case.
357
358 There is no alignment padding or any other extra data between fields.
359
360 Presently, all data values in a COPY BINARY file are assumed to be in
361 binary format (format code one). It is anticipated that a future exten‐
362 sion may add a header field that allows per-column format codes to be
363 specified.
364
365 To determine the appropriate binary format for the actual tuple data
366 you should consult the PostgreSQL source, in particular the *send and
367 *recv functions for each column's data type (typically these functions
368 are found in the src/backend/utils/adt/ directory of the source distri‐
369 bution).
370
371 If OIDs are included in the file, the OID field immediately follows the
372 field-count word. It is a normal field except that it's not included in
373 the field-count. In particular it has a length word — this will allow
374 handling of 4-byte vs. 8-byte OIDs without too much pain, and will
375 allow OIDs to be shown as null if that ever proves desirable.
376
377 FILE TRAILER
378 The file trailer consists of a 16-bit integer word containing -1. This
379 is easily distinguished from a tuple's field-count word.
380
381 A reader should report an error if a field-count word is neither -1 nor
382 the expected number of columns. This provides an extra check against
383 somehow getting out of sync with the data.
384
386 The following example copies a table to the client using the vertical
387 bar (|) as the field delimiter:
388
389 COPY country TO STDOUT WITH DELIMITER '|';
390
391
392 To copy data from a file into the country table:
393
394 COPY country FROM '/usr1/proj/bray/sql/country_data';
395
396
397 To copy into a file just the countries whose names start with 'A':
398
399 COPY (SELECT * FROM country WHERE country_name LIKE 'A%') TO '/usr1/proj/bray/sql/a_list_countries.copy';
400
401
402 Here is a sample of data suitable for copying into a table from STDIN:
403
404 AF AFGHANISTAN
405 AL ALBANIA
406 DZ ALGERIA
407 ZM ZAMBIA
408 ZW ZIMBABWE
409
410 Note that the white space on each line is actually a tab character.
411
412 The following is the same data, output in binary format. The data is
413 shown after filtering through the Unix utility od -c. The table has
414 three columns; the first has type char(2), the second has type text,
415 and the third has type integer. All the rows have a null value in the
416 third column.
417
418 0000000 P G C O P Y \n 377 \r \n \0 \0 \0 \0 \0 \0
419 0000020 \0 \0 \0 \0 003 \0 \0 \0 002 A F \0 \0 \0 013 A
420 0000040 F G H A N I S T A N 377 377 377 377 \0 003
421 0000060 \0 \0 \0 002 A L \0 \0 \0 007 A L B A N I
422 0000100 A 377 377 377 377 \0 003 \0 \0 \0 002 D Z \0 \0 \0
423 0000120 007 A L G E R I A 377 377 377 377 \0 003 \0 \0
424 0000140 \0 002 Z M \0 \0 \0 006 Z A M B I A 377 377
425 0000160 377 377 \0 003 \0 \0 \0 002 Z W \0 \0 \0 \b Z I
426 0000200 M B A B W E 377 377 377 377 377 377
427
428
430 There is no COPY statement in the SQL standard.
431
432 The following syntax was used before PostgreSQL version 7.3 and is
433 still supported:
434
435 COPY [ BINARY ] tablename [ WITH OIDS ]
436 FROM { 'filename' | STDIN }
437 [ [USING] DELIMITERS 'delimiter' ]
438 [ WITH NULL AS 'null string' ]
439
440 COPY [ BINARY ] tablename [ WITH OIDS ]
441 TO { 'filename' | STDOUT }
442 [ [USING] DELIMITERS 'delimiter' ]
443 [ WITH NULL AS 'null string' ]
444
445
446
447
448SQL - Language Statements 2008-06-08 COPY()