Sub topic 5
Exporting Tables and Query Results with `COPY TO`
Assume you know basic SELECT queries, CSV files, and how to use psql. This chapter focuses on exporting data from PostgreSQL. You will learn how to export a whole table, export a query result, and choose between server-side COPY and client-side \copy.
Exporting a whole table
COPY TO writes table data to a file or to an output stream. The following command exports every column and row from products:
COPY products TO '/var/lib/postgresql/export/products.csv'
WITH (FORMAT csv, HEADER true);FORMAT csv uses PostgreSQL's CSV rules. HEADER true writes one header row containing the column names.
The path in this SQL command is on the database server. PostgreSQL must be able to create the file there. The connected role also needs permission to write server-side files.
For most application workflows, the psql command \copy is easier:
\copy products TO 'products.csv' WITH (FORMAT csv, HEADER true)Although \copy looks similar, psql reads or writes the file on the client machine. PostgreSQL sends the table data through the database connection, and the local psql process writes products.csv.
Choosing between `COPY` and `\copy`
The two commands differ mainly in where the file exists.
flowchart LR
A[PostgreSQL table] --> B{Export command}
B -->|COPY TO filename| C[File on database server]
B -->|COPY TO STDOUT and psql \copy| D[File on client machine]The diagram shows the file location, not a difference in the exported CSV format. Both commands use PostgreSQL's CSV parser and formatter.
| Command | File location | Typical use |
|---|---|---|
| `COPY ... TO 'path'` | Database server | Controlled server-side jobs |
| `\copy ... TO 'path'` | Client machine | Developer exports and application scripts |
| `COPY ... TO STDOUT` | Output stream | Sending data through a client connection |
Use \copy when the data should land on your workstation or on the machine running a script. Use server-side COPY only when the database server has the required filesystem access and that access is acceptable.
Exporting a query result
COPY TO can export the result of a query instead of a complete table. Put the query in parentheses:
COPY (
SELECT id, name, price
FROM products
WHERE price > 10
ORDER BY id
) TO '/var/lib/postgresql/export/expensive.csv'
WITH (FORMAT csv, HEADER true);The equivalent client-side command is usually more convenient:
\copy (
SELECT id, name, price
FROM products
WHERE price > 10
ORDER BY id
) TO 'expensive.csv'
WITH (FORMAT csv, HEADER true)The output columns come from the query. Aliases become header names:
\copy (
SELECT id,
name AS product_name,
price * 1.20 AS price_with_tax
FROM products
ORDER BY id
) TO 'products_with_tax.csv'
WITH (FORMAT csv, HEADER true)Use ORDER BY when another system or a later comparison depends on row order. A table has no guaranteed natural order. Without ORDER BY, PostgreSQL can return the same rows in a different order after an index change, vacuum operation, or query-plan change.
CSV options and output streams
You can customize the CSV format when the receiving system expects different conventions:
\copy products TO 'products_semicolon.csv'
WITH (
FORMAT csv,
HEADER true,
DELIMITER ';',
NULL 'NULL'
)This uses semicolons between fields and writes the text NULL for SQL NULL values. Text containing the delimiter, quotes, or line breaks is quoted according to PostgreSQL's CSV rules.
For pipelines, export to standard output instead of naming a server file:
COPY (
SELECT id, name, price
FROM products
ORDER BY id
) TO STDOUT WITH (FORMAT csv, HEADER true);A client can receive that stream and save it locally. The psql form is:
psql "$DATABASE_URL" -c "\copy (SELECT id, name, price FROM products ORDER BY id) TO 'products.csv' WITH (FORMAT csv, HEADER true)"Verifying an export
Check the row count before exporting and compare it with the number of data lines afterward. A CSV file with a header has one more line than the number of rows only when fields do not contain embedded line breaks. For reliable verification, import the file into a test table and compare counts and key values.
Exercise
Which command should you normally use when the CSV file must be written on the computer running psql?
Show answer
Use psql's \copy command, because it writes the file on the client machine.