COPY(7)
COPY π (the PostgreSQL 18.6 era manual page, bestie edition)
okay so. you opened the man page for COPY and it's like forty screens long and ur brain went "nope" π« β but do not fret, babe, because this is genuinely one of the most iconic commands in all of PostgreSQL and we're gonna get through it together. this is part 1, so buckle in, hydrate, and let's go π
β¨ NAME β¨
COPY β copy data between a file and a table π¦
like. that's it. that's the whole vibe. data goes in, data comes out, files and tables are besties now π
β¨ SYNOPSIS β¨
okay this is the part where it looks like a wall of cryptic runes but it's literally just "here's how you type it". breathe. it's giving structured, actually πΈ
COPY table_name [ ( column_name [, ...] ) ]
FROM { 'filename' | PROGRAM 'command' | STDIN }
[ [ WITH ] ( option [, ...] ) ]
[ WHERE condition ]
COPY { table_name [ ( column_name [, ...] ) ] | ( query ) }
TO { 'filename' | PROGRAM 'command' | STDOUT }
[ [ WITH ] ( option [, ...] ) ]
and then, the moment you've all been waiting for, where option can be one of:
FORMAT format_name
FREEZE [ boolean ]
DELIMITER 'delimiter_character'
NULL 'null_string'
DEFAULT 'default_string'
HEADER [ boolean | MATCH ]
QUOTE 'quote_character'
ESCAPE 'escape_character'
FORCE_QUOTE { ( column_name [, ...] ) | * }
FORCE_NOT_NULL { ( column_name [, ...] ) | * }
FORCE_NULL { ( column_name [, ...] ) | * }
ON_ERROR error_action
REJECT_LIMIT maxerror
ENCODING 'encoding_name'
LOG_VERBOSITY verbosity
no cap, every single one of those gets its own little moment later on. we do not skip. skipping is not the vibe. π
β¨ DESCRIPTION β¨
so. COPY moves data between PostgreSQL tables and standard file-system files. that's the whole thesis statement bestie π«Ά
COPY TO copies the contents of a table to a file, while COPY FROM copies data from a file to a table β and heads up, it appends the data to whatever is in the table already, it does not wipe and replace, okay? no surprise deletions here π and plot twist: COPY TO can also copy the results of a SELECT query. main character energy fr fr β¨
if you specify a column list, here's the tea:
COPY TOcopies only the data in the specified columns to the file πCOPY FROMinserts each field in the file, in order, into the specified column. and any table columns you didn't name in theCOPY FROMcolumn list? they receive their default values π
okay so now the file stuff, and this is where people get confused so listen up πΈ
COPY with a file name tells the PostgreSQL server to directly read from or write to a file. important: that file must be accessible by the PostgreSQL user (aka the user ID the server runs as), and the name must be specified from the viewpoint of the server. not your laptop. not your home directory. the server. iykyk π
when PROGRAM is specified, the server executes the given command and reads from the standard output of the program, or writes to the standard input of the program. same deal: the command must be specified from the viewpoint of the server, and it has to be executable by the PostgreSQL user. π
when STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server. so it's travelling through the wire, cute π
fun lil bonus: each backend runningCOPYwill report its progress in thepg_stat_progress_copyview. see Section 27.4.3 for details π
and finally, the error behaviour, which honestly slays:
by default, COPY will fail if it encounters an error during processing. like, immediate stop, we're done here π
but for use cases where a best-effort attempt at loading the entire file is desired, the ON_ERROR clause can be used to specify some other behavior. obsessed with the flexibility honestly β¨
ok that's part 1!! more parts coming, don't go anywhere bestie π
π PARAMETERS π
okay bestie, here's the whole cast of characters you can pass in. every single one, no skips π«Ά
β¨ table_name
The name of an existing table β and yes, it can be schema-qualified if you're feeling fancy. π
β¨ column_name
An optional list of columns to copy. If you don't specify a list, all columns of the table get copied β except generated columns, those get left at home. π
β¨ query
A SELECT, VALUES, INSERT, UPDATE, DELETE, or MERGE command whose results are to be copied. And listen β parentheses are required around the query. yes literally, wrap it.
For INSERT, UPDATE, DELETE, and MERGE queries, a RETURNING clause must be provided, and the target relation must not have:
- a conditional rule
- an
ALSOrule - an
INSTEADrule that expands to multiple statements
that's the vibe check and it's non-negotiable π€
β¨ filename
The path name of the input or output file. An input file name can be an absolute or relative path, but an output file name must be an absolute path. Windows users might need to use an E'' string and double any backslashes used in the path name. π
β¨ PROGRAM
A command to execute. In COPY FROM, the input is read from the standard output of the command. In COPY TO, the output is written to the standard input of the command. π
β οΈ note that the command is invoked by the shell, so if you need to pass any arguments that come from an untrusted source, you must be careful to strip or escape any special characters that might have a special meaning for the shell. For security reasons, it is best to use a fixed command string, or at least avoid including any user input in it. fr fr, don't play with this one π
β¨ STDIN
Specifies that input comes from the client application. π¦
β¨ STDOUT
Specifies that output goes to the client application. β¨
β¨ boolean
Specifies whether the selected option should be turned on or off. You can write TRUE, ON, or 1 to enable the option, and FALSE, OFF, or 0 to disable it. The boolean value can also be omitted, in which case TRUE is assumed. slay, defaults doing the work for you π
β¨ FORMAT
Selects the data format to be read or written: text, csv (Comma Separated Values), or binary. The default is text. See File Formats below for details. π
β¨ FREEZE
Requests copying the data with rows already frozen, just as they would be after running the VACUUM FREEZE command. This is intended as a performance option for initial data loading. ποΈ
Rows will be frozen only if:
- the table being loaded has been created or truncated in the current subtransaction
- there are no cursors open
- there are no older snapshots held by this transaction
It is currently not possible to perform a COPY FREEZE on a partitioned table or foreign table. This option is only allowed in COPY FROM.
π¨ Note that all other sessions will immediately be able to see the data once it has been successfully loaded. This violates the normal rules of MVCC visibility and users should be aware of the potential problems this might cause. that's a big deal, bestie β know what you're signing up for π
β¨ DELIMITER
Specifies the character that separates columns within each row (line) of the file. The default is a tab character in text format, and a comma in CSV format. This must be a single one-byte character. This option is not allowed when using binary format. π
β¨ NULL
Specifies the string that represents a null value. The default is \N (backslash-N) in text format, and an unquoted empty string in CSV format. You might prefer an empty string even in text format for cases where you don't want to distinguish nulls from empty strings. This option is not allowed when using binary format.
π’ Note When usingCOPY FROM, 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 withCOPY TO. otherwise you're gonna have a bad time π
β¨ DEFAULT
Specifies the string that represents a default value. Each time the string is found in the input file, the default value of the corresponding column will be used. This option is allowed only in COPY FROM, and only when not using binary format. π
β¨ HEADER
Specifies that the file contains a header line with the names of each column in the file. On output, the first line contains the column names from the table. On input, the first line is discarded when this option is set to true (or equivalent Boolean value). If this option is set to MATCH, the number and names of the columns in the header line must match the actual column names of the table, in order; otherwise an error is raised. π¨
This option is not allowed when using binary format. The MATCH option is only valid for COPY FROM commands. π
β¨ QUOTE
Specifies the quoting character to be used when a data value is quoted. The default is double-quote. This must be a single one-byte character. This option is allowed only when using CSV format. β¨
β¨ ESCAPE
Specifies the character that should appear before a data character that matches the QUOTE value. The default is the same as the QUOTE value (so that the quoting character is doubled if it appears in the data). This must be a single one-byte character. This option is allowed only when using CSV format. π
β¨ FORCE_QUOTE
Forces quoting to be used for all non-NULL values in each specified column. NULL output is never quoted. If * is specified, non-NULL values will be quoted in all columns. This option is allowed only in COPY TO, and only when using CSV format. π
β¨ FORCE_NOT_NULL
Do not match the specified columns' values against the null string. In the default case where the null string is empty, this means that empty values will be read as zero-length strings rather than nulls, even when they are not quoted. If * is specified, the option will be applied to all columns. This option is allowed only in COPY FROM, and only when using CSV format. π
β¨ FORCE_NULL
Match the specified columns' values against the null string, even if it has been quoted, and if a match is found set the value to NULL. In the default case where the null string is empty, this converts a quoted empty string into NULL. If * is specified, the option will be applied to all columns. This option is allowed only in COPY FROM, and only when using CSV format. π
β¨ ON_ERROR
Specifies how to behave when encountering an error converting a column's input value into its data type. An error_action value of stop means fail the command, while ignore means discard the input row and continue with the next one. The default is stop. π€
The ignore option is applicable only for COPY FROM when the FORMAT is text or csv.
A NOTICE message containing the ignored row count is emitted at the end of the COPY FROM if at least one row was discarded. When LOG_VERBOSITY option is set to verbose, a NOTICE message containing the line of the input file and the column name whose input conversion has failed is emitted for each discarded row. When it is set to silent, no message is emitted regarding ignored rows. π€«
β¨ REJECT_LIMIT
Specifies the maximum number of errors tolerated while converting a column's input value to its data type, when ON_ERROR is set to ignore. If the input causes more errors than the specified value, the COPY command fails, even with ON_ERROR set to ignore. π
This clause must be used with ON_ERROR=ignore and maxerror must be positive bigint. If not specified, ON_ERROR=ignore allows an unlimited number of errors, meaning COPY will skip all erroneous data. no cap, unlimited π«Ά
β¨ ENCODING
Specifies that the file is encoded in the encoding_name. If this option is omitted, the current client encoding is used. See the Notes below for more details. π¦
β¨ LOG_VERBOSITY
Specifies the amount of messages emitted by a COPY command: default, verbose, or silent. If verbose is specified, additional messages are emitted during processing. silent suppresses both verbose and default messages.
This is currently used in COPY FROM command when ON_ERROR option is set to ignore. π
β¨ WHERE
The optional WHERE clause has the general form
WHERE condition
where condition is any expression that evaluates to a result of type boolean. Any row that does not satisfy this condition will not be inserted to the table. A row satisfies the condition if it returns true when the actual row values are substituted for any variable references. β¨
Currently, subqueries and generated columns are not allowed in WHERE expressions, and the evaluation does not see any changes made by the COPY itself (this matters when the expression contains calls to VOLATILE functions). π
π OUTPUTS π
On successful completion, a COPY command returns a command tag of the form
COPY count
The count is the number of rows copied. π₯
π’ Notepsqlwill print this command tag only if the command was notCOPY ... TO STDOUT, or the equivalentpsqlmeta-command\copy ... to stdout. This is to prevent confusing the command tag with the data that was just printed. iykyk, otherwise you'd be reading your own output like π
π NOTES π
okay so before you go off and COPY everything in sight, bestie, there's some lore you need. sit down, hydrate, let's go π«Ά
COPY TOcan be used with plain tables and populated materialized views. like, for example,COPY table TOcopies the exact same rows asSELECT * FROM ONLY table. but it does not directly support other relation types, such as partitioned tables, inheritance child tables, or views. so if you wanna copy all the rows from those, you gotta doCOPY (SELECT * FROM table) TO. iykyk πCOPY FROMcan be used with plain, foreign, or partitioned tables, or with views that haveINSTEAD OF INSERTtriggers. versatile queen π- privileges check β¨ you must have select privilege on the table whose values are read by
COPY TO, and insert privilege on the table into which values are inserted byCOPY FROM. and ngl, it is sufficient to have column privileges on the column(s) listed in the command. so you don't need the whole table's blessing, just the columns you're touching π - row-level security β if row-level security is enabled for the table, the relevant
SELECTpolicies will apply toCOPY table TOstatements. but currently,COPY FROMis not supported for tables with row-level security. use equivalentINSERTstatements instead, bestie, no cap π - the server is doing the file stuff, not the client π₯ files named in a
COPYcommand are read or written directly by the server, not by the client application. therefore, they must reside on or be accessible to the database server machine, not the client. they must be accessible to and readable or writable by the PostgreSQL user (the user ID the server runs as), not the client. similarly, the command specified withPROGRAMis executed directly by the server, not by the client application, and must be executable by the PostgreSQL user. and listen:COPYnaming a file or command is only allowed to database superusers or users who are granted one of the rolespg_read_server_files,pg_write_server_files, orpg_execute_server_program, since it allows reading or writing any file or running a program that the server has privileges to access. that's a lot of power, main character energy, handle with care π
do not confuseCOPYwith the psql instruction\copy.\copyinvokesCOPY FROM STDINorCOPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. thus, file accessibility and access rights depend on the client rather than the server when\copyis used. two different vibes entirely π
- absolute paths, please it is recommended that the file name used in
COPYalways be specified as an absolute path. this is enforced by the server in the case ofCOPY TO, but forCOPY FROMyou do have the option of reading from a file specified by a relative path. the path will be interpreted relative to the working directory of the server process (normally the cluster's data directory), not the client's working directory. don't get it twisted πΈ PROGRAMrestrictions β executing a command withPROGRAMmight be restricted by the operating system's access control mechanisms, such as SELinux. lowkey annoying but that's the OS's business π¦- triggers and constraints β
COPY FROMwill invoke any triggers and check constraints on the destination table. however, it will not invoke rules. periodt. - identity columns β for identity columns, the
COPY FROMcommand will always write the column values provided in the input data, like theINSERToptionOVERRIDING SYSTEM VALUE. it said what it said π DateStylegirlies βCOPYinput and output is affected byDateStyle. to ensure portability to other PostgreSQL installations that might use non-defaultDateStylesettings,DateStyleshould be set toISObefore usingCOPY TO. it is also a good idea to avoid dumping data withIntervalStyleset tosql_standard, because negative interval values might be misinterpreted by a server that has a different setting forIntervalStyle. protect your data's peace π- encoding β input data is interpreted according to the
ENCODINGoption or the current client encoding, and output data is encoded inENCODINGor the current client encoding, even if the data does not pass through the client but is read from or written to a file directly by the server. the encoding follows you everywhere, iconic behavior β¨ - β οΈ disk space warning, this one's serious β οΈ the
COPY FROMcommand physically inserts input rows into the table as it progresses. if the command fails, these rows are left in a deleted state; these rows will not be visible, but still occupy disk space. this might amount to considerable wasted disk space if the failure happened well into a large copy operation.VACUUMshould be used to recover the wasted space. fr fr, go vacuum π§Ή FORCE_NULL+FORCE_NOT_NULLcan be used simultaneously on the same column. this results in converting quoted null strings to null values and unquoted null strings to empty strings. both at once, chaotic but valid π
π FILE FORMATS π
πΈ Text Format πΈ
when the text format is used, the data read or written is a text file with one line per table row. columns in a row are separated by the delimiter character. the column values themselves are strings generated by the output function, or acceptable to the input function, of each attribute's data type. the specified null string is used in place of columns that are null. and COPY FROM will raise an error if any line of the input file contains more or fewer columns than are expected. match the count, bestie π
end of data can be represented by a line containing just backslash-period (\.). an end-of-data marker is not necessary when reading from a file, since the end of file serves perfectly well; in that context this provision exists only for backward compatibility. however, psql uses \. to terminate a COPY FROM STDIN operation (that is, reading in-line COPY data in an SQL script). in that context the rule is needed to be able to end the operation before the end of the script. iykyk π
backslash characters (\) can be used in the COPY data to quote data characters that might otherwise be taken as row or column delimiters. in particular, the following characters must be preceded by a backslash if they appear as part of a column value: backslash itself, newline, carriage return, and the current delimiter character. don't skip any of those π«Ά
the specified null string is sent by COPY TO without adding any backslashes; conversely, COPY FROM matches the input against the null string before removing backslashes. therefore, a null string such as \N cannot be confused with the actual data value \N (which would be represented as \\N). sneaky but correct π
the following special backslash sequences are recognized by COPY FROM:
\bβ Backspace (ASCII 8)\fβ Form feed (ASCII 12)\nβ Newline (ASCII 10)\rβ Carriage return (ASCII 13)\tβ Tab (ASCII 9)\vβ Vertical tab (ASCII 11)\digitsβ Backslash followed by one to three octal digits specifies the byte with that numeric code\xdigitsβ Backslash x followed by one or two hex digits specifies the byte with that numeric code
presently, COPY TO will never emit an octal or hex-digits backslash sequence, but it does use the other sequences listed above for those control characters. slay, consistent output β¨
any other backslashed character that is not mentioned in the above table will be taken to represent itself. however, beware of adding backslashes unnecessarily, since that might accidentally produce a string matching the end-of-data marker (\.) or the null string (\N by default). these strings will be recognized before any other backslash processing is done. so like... chill with the backslashes π
strongly recommended, no cap: applications generatingCOPYdata should convert data newlines and carriage returns to the\nand\rsequences respectively. at present it is possible to represent a data carriage return by a backslash and carriage return, and to represent a data newline by a backslash and newline. however, these representations might not be accepted in future releases. they are also highly vulnerable to corruption if theCOPYfile is transferred across different machines (for example, from Unix to Windows or vice versa). so like, do it the right way the first time π
all backslash sequences are interpreted after encoding conversion. the bytes specified with the octal and hex-digit backslash sequences must form valid characters in the database encoding. no invalid bytes in this house π«
COPY TO will terminate each row with a Unix-style newline ("\n"). servers running on Microsoft Windows instead output carriage return/newline ("\r\n"), but only for COPY to a server file; for consistency across platforms, COPY TO STDOUT always sends "\n" regardless of server platform. COPY FROM can handle lines ending with newlines, carriage returns, or carriage return/newlines. to reduce the risk of error due to un-backslashed newlines or carriage returns that were meant as data, COPY FROM will complain if the line endings in the input are not all alike. consistency check, periodt β
π CSV Format π
this format option is used for importing and exporting the Comma-Separated Value (CSV) file format used by many other programs, such as spreadsheets. instead of the escaping rules used by PostgreSQL's standard text format, it produces and recognizes the common CSV escaping mechanism. it's giving spreadsheet energy π
the values in each record are separated by the DELIMITER character. if the value contains the delimiter character, the QUOTE character, the NULL string, a carriage return, or line feed character, then the whole value is prefixed and suffixed by the QUOTE character, and any occurrence within the value of a QUOTE character or the ESCAPE character is preceded by the escape character. you can also use FORCE_QUOTE to force quotes when outputting non-NULL values in specific columns. cute, controlled, precise π¦
The CSV format has no standard way to tell a NULL value apart from an empty string. π Like, they're both just... nothing? So PostgreSQL's COPY handles it with quoting. A NULL is output as the NULL parameter string and is not quoted, while a non-NULL value that happens to match the NULL parameter string is quoted. For example, with the default settings, a NULL is written as an unquoted empty string, while an empty string data value is written with double quotes (""). Reading values follows similar rules. You can use FORCE_NOT_NULL to prevent NULL input comparisons for specific columns. You can also use FORCE_NULL to convert quoted null string data values to NULL. π
Because backslash is not a special character in the CSV format, the end-of-data marker used in text mode (\.) is not normally treated as special when reading CSV data. The one exception? psql will terminate a COPY FROM STDIN operation (that is, reading in-line COPY data in an SQL script) at a line containing only \., whether it is text or CSV mode. π
Note β PostgreSQL versions before v18 always recognized unquoted\.as an end-of-data marker, even when reading from a separate file. For compatibility with older versions,COPY TOwill quote\.when it's alone on a line, even though this is no longer necessary.
Note β In CSV format, all characters are significant. A quoted value surrounded by white space, or any characters other than DELIMITER, will include those characters. This can cause errors if you import data from a system that pads CSV lines with white space out to some fixed width. If such a situation arises you might need to preprocess the CSV file to remove the trailing white space, before importing the data into PostgreSQL.
Note β CSV format will both recognize and produce CSV files with quoted values containing embedded carriage returns and line feeds. So the files are not strictly one line per table row like text-format files. π
Note β Many programs produce strange and occasionally perverse CSV files, so the file format is more a convention than a standard. Thus you might encounter some files that cannot be imported using this mechanism, and COPY might produce files that other programs cannot process. It's giving chaos, honestly.
π Binary Format π
The binary format option causes all data to be stored/read as binary format rather than as text. It is somewhat faster than the text and CSV formats, but a binary-format file is less portable across machine architectures and PostgreSQL versions. π¬ Also, the binary format is very data type specific; for example it will not work to output binary data from a smallint column and read it into an integer column, even though that would work fine in text format. No cap.
The binary file format consists of a file header, zero or more tuples containing the row data, and a file trailer. Headers and data are in network byte order. π§
Note β PostgreSQL releases before 7.4 used a different binary file format. Ancient history bestie.
File Header
The file header consists of 15 bytes of fixed fields, followed by a variable-length header extension area. The fixed fields are:
- Signature β 11-byte sequence
PGCOPY\n\377\r\n\0β note that the zero byte is a required part of the signature. (The signature is designed to allow easy identification of files that have been munged by a non-8-bit-clean transfer. This signature will be changed by end-of-line-translation filters, dropped zero bytes, dropped high bits, or parity changes.) π - Flags field β 32-bit integer bit mask to denote important aspects of the file format. Bits are numbered from 0 (LSB) to 31 (MSB). Note that this field is stored in network byte order (most significant byte first), as are all the integer fields used in the file format. Bits 16β31 are reserved to denote critical file format issues; a reader should abort if it finds an unexpected bit set in this range. Bits 0β15 are reserved to signal backwards-compatible format issues; a reader should simply ignore any unexpected bits set in this range. Currently only one flag bit is defined, and the rest must be zero:
- Bit 16 β If 1, OIDs are included in the data; if 0, not. Oid system columns are not supported in PostgreSQL anymore, but the format still contains the indicator.
- Header extension area length β 32-bit integer, length in bytes of remainder of header, not including self. Currently, this is zero, and the first tuple follows immediately. Future changes to the format might allow additional data to be present in the header. A reader should silently skip over any header extension data it does not know what to do with.
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. π«Ά
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).
Tuples
Each tuple begins with a 16-bit integer count of the number of fields in the tuple. (Presently, all tuples in a table will have the same count, but that might not always be true.) Then, repeated for each field in the tuple, there is a 32-bit length word followed by that many bytes of field data. (The length word does not include itself, and can be zero.) As a special case, -1 indicates a NULL field value. No value bytes follow in the NULL case. π
There is no alignment padding or any other extra data between fields. Clean. Minimal. Iconic.
Presently, all data values in a binary-format file are assumed to be in binary format (format code one). It is anticipated that a future extension might add a header field that allows per-column format codes to be specified.
To determine the appropriate binary format for the actual tuple data you should consult the PostgreSQL source, in particular the *send and *recv functions for each column's data type (typically these functions are found in the src/backend/utils/adt/ directory of the source distribution). π
If OIDs are included in the file, the OID field immediately follows the field-count word. It is a normal field except that it's not included in the field-count. Note that oid system columns are not supported in current versions of PostgreSQL.
File Trailer
The file trailer consists of a 16-bit integer word containing -1. This is easily distinguished from a tuple's field-count word. β¨
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.
π EXAMPLES π
The following example copies a table to the client using the vertical bar (|) as the field delimiter:
COPY country TO STDOUT (DELIMITER '|');
To copy data from a file into the country table:
COPY country FROM '/usr1/proj/bray/sql/country_data';
To copy into a file just the countries whose names start with 'A':
COPY (SELECT * FROM country WHERE country_name LIKE 'A%') TO '/usr1/proj/bray/sql/a_list_countries.copy';
To copy into a compressed file, you can pipe the output through an external compression program:
COPY country TO PROGRAM 'gzip > /usr1/proj/bray/sql/country_data.gz';
Here is a sample of data suitable for copying into a table from STDIN:
AF AFGHANISTAN
AL ALBANIA
DZ ALGERIA
ZM ZAMBIA
ZW ZIMBABWE
Note that the white space on each line is actually a tab character. π
The following is the same data, output in binary format. The data is shown after filtering through the Unix utility od -c. The table has three columns; the first has type char(2), the second has type text, and the third has type integer. All the rows have a null value in the third column.
0000000 P G C O P Y \n 377 \r \n \0 \0 \0 \0 \0 \0
0000020 \0 \0 \0 \0 003 \0 \0 \0 002 A F \0 \0 \0 013 A
0000040 F G H A N I S T A N 377 377 377 377 \0 003
0000060 \0 \0 \0 002 A L \0 \0 \0 007 A L B A N I
0000100 A 377 377 377 377 \0 003 \0 \0 \0 002 D Z \0 \0 \0
0000120 007 A L G E R I A 377 377 377 377 \0 003 \0 \0
0000140 \0 002 Z M \0 \0 \0 006 Z A M B I A 377 377
0000160 377 377 \0 003 \0 \0 \0 002 Z W \0 \0 \0 \b Z I
0000200 M B A B W E 377 377 377 377 377 377
π COMPATIBILITY π
There is no COPY statement in the SQL standard. π€·βοΈ We're built different.
The following syntax was used before PostgreSQL version 9.0 and is still supported:
COPY table_name [ ( column_name [, ...] ) ]
FROM { 'filename' | STDIN }
[ [ WITH ]
[ BINARY ]
[ DELIMITER [ AS ] 'delimiter_character' ]
[ NULL [ AS ] 'null_string' ]
[ CSV [ HEADER ]
[ QUOTE [ AS ] 'quote_character' ]
[ ESCAPE [ AS ] 'escape_character' ]
[ FORCE NOT NULL column_name [, ...] ] ] ]
COPY { table_name [ ( column_name [, ...] ) ] | ( query ) }
TO { 'filename' | STDOUT }
[ [ WITH ]
[ BINARY ]
[ DELIMITER [ AS ] 'delimiter_character' ]
[ NULL [ AS ] 'null_string' ]
[ CSV [ HEADER ]
[ QUOTE [ AS ] 'quote_character' ]
[ ESCAPE [ AS ] 'escape_character' ]
[ FORCE QUOTE { column_name [, ...] | * } ] ] ]
Note that in this syntax, BINARY and CSV are treated as independent keywords, not as arguments of a FORMAT option.
The following syntax was used before PostgreSQL version 7.3 and is still supported:
COPY [ BINARY ] table_name
FROM { 'filename' | STDIN }
[ [USING] DELIMITERS 'delimiter_character' ]
[ WITH NULL AS 'null_string' ]
COPY [ BINARY ] table_name
TO { 'filename' | STDOUT }
[ [USING] DELIMITERS 'delimiter_character' ]
[ WITH NULL AS 'null_string' ]
π¦ SEE ALSO π¦
Section 27.4.3
And that's the whole page, bestie β you made it to the end and honestly? Main character energy. π«Ά This one came from PostgreSQL 18.6, dated 2026, and it's the COPY(7) manual page. Now go forth and copy some data, you gorgeous little data wizard. πβ¨πΈ
π¦ where this page comes from
- alpine 3.23: postgresql18-doc 18.6-r0 Β· PostgreSQL
- alpine 3.24: postgresql18-doc 18.6-r0 Β· PostgreSQL
- arch rolling: postgresql 18.6-4 Β· PostgreSQL
- fedora 43: postgresql 18.6-1.fc43 Β· PostgreSQL
- fedora 43: postgresql 18.6-1.fc43 Β· PostgreSQL
- fedora 44: postgresql 18.6-1.fc44 Β· PostgreSQL
- fedora 44: postgresql 18.6-1.fc44 Β· PostgreSQL
- nixos 26.05: postgresql 18.6
- ubuntu resolute: postgresql-client-18 18.6-0ubuntu0.26.04.1 Β· PostgreSQL
- ubuntu stonking: postgresql-client-18 18.6-3build2 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms