Sub topic 5
Exporting tables and query results with COPY TO
This chapter assumes you can write SELECT queries and use psql. It also assumes you have read the earlier chapters on COPY basics, the CSV format options, and server-side COPY versus \copy. The examples use the products table from earlier in the tutorial. Here it holds four rows:
INSERT INTO products (id, name, price, released, notes) VALUES
(1, 'Widget', 9.99, '2024-03-01', NULL),
(2, 'Gadget, large', 24.50, '2024-05-12', 'Says "new"'),
(3, 'Gizmo', 15.00, NULL, ''),
(4, 'Thing', 5.00, '2023-11-30', E'line one\nline two');What COPY TO does
COPY ... TO writes rows out of PostgreSQL in a streaming format. The source is either a table or the result of a query. The destination is a file, the client connection (STDOUT), or a program. COPY does not build a result set in client memory the way a normal SELECT does in most drivers. It sends rows as it produces them, so it suits large exports.
There are two forms of the source:
COPY table_name [ (column_list) ] TO destination WITH (options);
COPY (query) TO destination WITH (options);The query form needs the parentheses. The query can be a SELECT or VALUES. It can also be an INSERT, UPDATE, or DELETE that has a RETURNING clause, which lets you change rows and export the affected rows in one statement.
Exporting a whole table
The simplest export names the table and writes CSV to STDOUT:
COPY products TO STDOUT WITH (FORMAT csv, HEADER true);For the sample data, psql prints this:
id,name,price,released,notes
1,Widget,9.99,2024-03-01,
2,"Gadget, large",24.50,2024-05-12,"Says ""new"""
3,Gizmo,15.00,,""
4,Thing,5.00,2023-11-30,"line one
line two"Look at what COPY did with each awkward value:
- A field containing the delimiter, a quote, or a newline is wrapped in double quotes. Embedded quotes are doubled.
- Row 1 has a NULL
notes, written as nothing at all. Row 3 has an empty string, written as"". The two stay distinguishable. The next chapter covers this in detail. - The
HEADER trueoption writes a first line of column names. Without it, the file has data rows only. - Row 4 spans two physical lines, so the file has more lines than the table has rows.
When you do not give a column list, COPY writes every column in table order. Dates, timestamps, and numbers are written in their text form, which depends on session settings such as DateStyle and TimeZone. With the default ISO style the output is stable, but a session with a different DateStyle produces differently formatted dates. Consumers of your file will be happier if you set the style explicitly in scripts.
Choosing columns
A column list limits and orders the output:
COPY products (name, id) TO STDOUT WITH (FORMAT csv, HEADER true);The header line and every row follow the order you list, not the table's order. This is useful when a downstream tool expects a fixed layout.
Exporting a query result
A query gives you filtering, joins, computed columns, and ordering. The query form is the one you will use most:
\copy (SELECT id, name, price FROM products WHERE price > 10 ORDER BY id) TO 'expensive.csv' WITH (FORMAT csv, HEADER true)Three points about the query form:
- Add ORDER BY if order matters. PostgreSQL returns rows in no guaranteed order. Two exports of the same table can differ, which makes file comparisons noisy.
- Name computed columns. The header uses the query's output column names. An expression such as
price * 1.2gets an unhelpful name unless you writeAS price_with_tax. - Use the query form for views, inheritance, and partitions.
COPY table TOwrites only rows stored directly in that table. It does not read child tables in an inheritance hierarchy, and it cannot take a view as its source. WriteCOPY (SELECT * FROM the_view) TO ...for a view, an inheritance parent, or a partitioned table, and you get all the rows.
The output column names and types come from the query, so you can reshape data on the way out:
\copy (SELECT id, upper(name) AS name, price::text AS price_text, coalesce(released::text, 'unknown') AS released FROM products ORDER BY id) TO 'report.csv' WITH (FORMAT csv, HEADER true)Where the output goes
The destination decides which machine writes the data and which privileges you need.
| Destination | Written by | Typical use |
|---|---|---|
| `COPY ... TO '/path/file.csv'` | The server process, on the server's disk | Server-side exports where you control the host |
| `\copy ... TO 'file.csv'` | psql, on your machine | Everyday exports, managed databases |
| `COPY ... TO STDOUT` | Streamed to the client | Pipes, drivers, redirecting in shell scripts |
| `COPY ... TO PROGRAM 'cmd'` | A command run by the server | Compressing on the server (restricted) |
| `\copy ... TO PROGRAM 'cmd'` | A command run by psql on the client | Compressing locally |
A server-side path is resolved by the PostgreSQL server process. The file is owned by the operating system account that runs the server, and the account must be able to write to that directory. You need the pg_write_server_files role or superuser rights. Writing to an existing path overwrites it. On managed services such as RDS you usually cannot use this form at all, which is one reason \copy is the default choice.
\copy runs COPY ... TO STDOUT under the hood and has psql save the stream to a local file. Your database role needs only SELECT on the source, and the file is written with your own operating system permissions. Two psql rules apply to \copy. The whole command must fit on one line, and it does not end with a semicolon.
Exporting from a script
Because STDOUT is just a stream, you can redirect it in the shell. This pattern avoids any file option and works well in pipelines:
psql "$DATABASE_URL" -c "\copy (SELECT * FROM products ORDER BY id) TO STDOUT WITH (FORMAT csv, HEADER true)" | gzip > products.csv.gzFor a client-side compressed file in one step, use PROGRAM:
\copy (SELECT * FROM products ORDER BY id) TO PROGRAM 'gzip > products.csv.gz' WITH (FORMAT csv, HEADER true)Quote shell metacharacters carefully if any part of the command comes from user input. Never build these commands from untrusted values.
Format options that matter on export
The options are the ones you met in the CSV chapter, but a few behave differently when writing:
DELIMITERsets the separator. UseDELIMITER ';'for tools that expect semicolons. A field containing that character is quoted automatically.QUOTEandESCAPEcontrol how embedded quotes are written. In CSV the default for both is the double quote, which produces the""doubling you saw above.NULLsets the text that stands for a NULL. In CSV the default is an empty, unquoted field. SettingNULL 'NULL'writes the word instead. Choose the same string you will use when reading the file back.FORCE_QUOTEis valid only for output. It quotes every non-NULL value in the listed columns, or in all columns with*. Some consumers need quoted text so that identifiers like007or1E5are not read as numbers.ENCODINGconverts the output to a given character set, for exampleENCODING 'UTF8'. Without it, COPY uses the client encoding. If a spreadsheet shows garbled accents, check this first.HEADERwrites column names. It is a plain on/off choice when exporting.
A combined example for a semicolon-delimited file with explicit NULLs and quoted names:
\copy (SELECT id, name, price, released, notes FROM products ORDER BY id) TO 'products_semicolon.csv' WITH (FORMAT csv, HEADER true, DELIMITER ';', NULL 'NULL', FORCE_QUOTE (name))Note that FORCE_QUOTE with a NULL value does not quote the NULL marker. NULLs remain unquoted, so a reader can still tell them apart from the string "NULL".
Counting what you wrote
COPY finishes with a command tag such as COPY 4, which is the number of rows written. psql shows it for \copy to a file. When you send output to STDOUT, psql may not show the tag in the terminal, so check the file instead.
Counting lines with wc -l gives the row count plus one for the header, but only when no field contains a line break. In the sample data, row 4 contains a newline, so wc -l reports 7 lines for 4 rows plus a header (header, rows 1 to 3, and two lines for row 4 make 6 lines; the sixth line ends with a newline, so wc -l prints 6). To check an export reliably, compare the row count the server reports with a CSV-aware count, for example one done in the tool that will read the file. The chapter on verification returns to this.
Failure modes
- Partial files. COPY streams rows. If the connection drops or a query error occurs midway, such as a division by zero in an expression, the file may contain rows written before the error. Treat a failed export as unusable and delete it. In scripts, export to a temporary name and rename the file after the command succeeds.
- Permission denied on a server path. The server account cannot write the directory, even if your login can. Choose a directory owned by the server account, or switch to
\copy. - Must be superuser or have pgwriteserver_files. You used a server-side path without the role. Use
\copyinstead of asking for broader rights. - Relative paths. A server-side
COPYneeds an absolute path. A relative path in\copyis relative to psql's working directory. - Snapshot consistency. A single COPY sees one consistent snapshot of the data, so it is safe against concurrent writes. Two separate COPY commands do not share a snapshot. If you export several related tables, use a
REPEATABLE READtransaction around all of them.
BEGIN ISOLATION LEVEL REPEATABLE READ;
\copy (SELECT * FROM products ORDER BY id) TO 'products.csv' WITH (FORMAT csv, HEADER true)
\copy (SELECT * FROM orders ORDER BY id) TO 'orders.csv' WITH (FORMAT csv, HEADER true)
COMMIT;This example assumes you also have an orders table.
A complete export check
The script below exports the table, counts rows in the database, and counts lines in the file. For data without embedded newlines, the file line count is the row count plus one:
psql "$DATABASE_URL" -c "\copy (SELECT * FROM products ORDER BY id) TO 'products_export.csv' WITH (FORMAT csv, HEADER true)"
psql "$DATABASE_URL" -c "SELECT count(*) FROM products"
wc -l products_export.csvExercise
You need all rows from a partitioned table events in one CSV with a header, ordered by id, written on your laptop. Which statement do you use, and why not COPY events TO ...?
Show answer
Use \copy (SELECT * FROM events ORDER BY id) TO 'events.csv' WITH (FORMAT csv, HEADER true). The query form returns rows from every partition, which COPY events TO may not, since the table form copies only rows stored directly in the named table. \copy writes the file on your machine and needs only SELECT privilege.
Exercise
An export of the sample products table with FORMAT csv shows notes empty for row 1 and "" for row 3. What does this tell you about the data, and which option would make NULLs explicit?
Show answer
Row 1 has a NULL notes value, and row 3 has an empty string. CSV output writes NULL as an unquoted empty field and an empty string as a quoted "". Adding NULL 'NULL' to the options writes the word NULL for missing values.
Exercise
A colleague exported 1,000 rows with a header and wc -l reports 1,012 lines. Give the most likely cause and a way to confirm it.
Show answer
Some fields contain embedded newlines, which COPY keeps inside quoted fields, so one row spans several lines. Confirm by loading the file with a CSV-aware reader, or by comparing against SELECT count(*), or by searching the source column with WHERE column LIKE '%' || chr(10) || '%'.