Export PostgreSQL query results to CSV on the correct machine

A PostgreSQL export can write a file on the client machine or on the database server. The SQL query can be identical, but the path and operating-system permissions belong to different processes. Use psql's \copy when you want the file beside the client you are running.

Export a query result rather than trying to capture a formatted console table. PostgreSQL's CSV writer handles delimiters and quotes correctly, while an ordinary text display is intended for people rather than a CSV parser.

Check the rows and choose the destination

This read-only fixture has a comma, a double quote, a NULL and an empty string. It touches no application table.

SQL
SELECT id, display_name
FROM (VALUES
    (1, 'Ada, Jr.'),
    (2, 'Lin "L"'),
    (3, NULL),
    (4, '')
) AS Demo(id, display_name)
ORDER BY id;

Run the query first and confirm four rows. Before either export, choose a new output filename in a directory you own. The client form can replace an existing local file, and server-side behavior and permissions differ. Do not use a valuable existing file as the destination.

Each alternative below includes the complete query. Choose one. Both request a header and UTF-8 encoding, and both preserve row order through ORDER BY id.

πŸ’»Client file

Write the file with psql

Enter this as one physical line at the psql prompt. The backslash command is interpreted by psql, so it is not a SQL statement to send through an arbitrary database driver.

Plain text
\copy (SELECT id, display_name FROM (VALUES (1, 'Ada, Jr.'), (2, 'Lin "L"'), (3, NULL), (4, '')) AS Demo(id, display_name) ORDER BY id) TO './query-export-demo.csv' WITH (FORMAT csv, HEADER true, ENCODING 'UTF8')

The path is relative to psql's local working directory. psql receives the query output through the connection and writes it using your local file permissions. This approach does not require granting the database role broad server-file access.

psql's \copy has its own argument-parsing rules. Keep the command on one line as shown. If a GUI offers a query-export feature, inspect that client's destination and formatting choices rather than assuming it implements this exact meta-command.

πŸ—„οΈServer file

Write the file on the database server

Use this alternative only when server-side export is the intended workflow. Replace the absolute placeholder path with a new approved path on the server before executing it.

SQL
COPY (
    SELECT id, display_name
    FROM (VALUES
        (1, 'Ada, Jr.'),
        (2, 'Lin "L"'),
        (3, NULL),
        (4, '')
    ) AS Demo(id, display_name)
    ORDER BY id
) TO '/approved/export/query-export-demo.csv'
WITH (FORMAT csv, HEADER true, ENCODING 'UTF8');

The server process writes this file. PostgreSQL requires the relevant server-file privilege, such as an appropriately administered pg_write_server_files role, as well as operating-system access for the database service. This example does not grant those privileges. A desktop path does not become accessible to a remote server merely because it appears in the SQL text.

Verify the CSV contract

Expected file contents, apart from platform line endings:

Plain text
id,display_name
1,"Ada, Jr."
2,"Lin ""L"""
3,
4,""

The comma-containing field is quoted, and the embedded quote is doubled. With PostgreSQL's default CSV NULL representation, the unquoted empty field in row 3 means NULL, while row 4's quoted empty field means an empty string. A generic CSV reader may not retain that distinction, so agree on the import contract with the consuming system.

An export file is not rolled back with a database transaction. A failed export can also leave an incomplete file. Check command success and the expected row count before handing the output to another process, and use a new filename rather than exposing a partially written report as the final artifact.

For a set-returning function, the same pattern can export a SELECT from that function. A PL/pgSQL RAISE NOTICE message is diagnostic output rather than a relational result, so redesign that boundary if the intended data currently exists only in notices.

Source and further reading

This article addresses the problem raised by Hoff in β€œSave PL/pgSQL output from PostgreSQL to a CSV file” on Stack Overflow, licensed under CC BY-SA 3.0 . The question is the topic source. The explanations and examples here are newly authored from the database documentation, rather than reproduced from a community answer.

COPY
COPY COPY β€” copy data between a file and a table Synopsis COPY table_name [ ( column_name [, ...] ) …
https://www.postgresql.org/docs/current/sql-copy.html
psql
psql psql β€” PostgreSQL interactive terminal Synopsis psql [option...] [dbname [username]] Description psql is a terminal-based front-end to PostgreSQL. It …
https://www.postgresql.org/docs/current/app-psql.html

Author: Herman Schoenfeld