Export Rows To CSV With COPY

Stream query results out as CSV with COPY ... TO STDOUT: headers on demand, RFC 4180 quoting for commas and quotes, forced quotes per column.

SqlData Fetching

Code

snippet
-- 导出 CSV:COPY (...) TO STDOUT,客户端流式拿到文件内容
-- psql 里用 \copy (…) TO 'done.csv' WITH (FORMAT csv, HEADER true) 直接落盘
COPY (
    SELECT *
    FROM (VALUES
        (1, 'nightly-report', 'done'),
        (2, 'billing, retry job', 'done'),
        (3, 'say "hi"', 'done')
    ) AS t(id, title, status)
    WHERE status = 'done'
    ORDER BY id
) TO STDOUT WITH (FORMAT csv, HEADER true);

-- 输出(值含逗号/引号时按 RFC 4180 自动加引号转义):
-- id,title,status
-- 1,nightly-report,done
-- 2,"billing, retry job",done
-- 3,"say ""hi""",done

-- 只给某列强制加引号:FORCE_QUOTE (title)
-- 写到服务端文件:TO '/var/lib/postgresql/export.csv',需要 pg_write_server_files 角色

How it works

What runs is SELECT.

The pieces that do the work: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.

The whole export is a single COPY statement wrapping a SELECT over a VALUES list aliased t(id, title, status), and TO STDOUT streams the rendered rows to the client rather than writing a file on the server.

WITH (FORMAT csv, HEADER true) picks CSV output with a leading header row, so the expected output in the comment starts with id,title,status before the three data rows.

Quoting follows RFC 4180: the comma inside 'billing, retry job' forces quotes around that field, the embedded quotes in 'say "hi"' double to "", while a plain value like nightly-report is emitted bare.

The trailing comment lines show the variations: psql’s \copy form writes done.csv on the client, FORCE_QUOTE (title) quotes one column unconditionally, and a server-side target such as /var/lib/postgresql/export.csv requires the pg_write_server_files role.

Key statements

COPY (
SELECT *
FROM (VALUES
(1, 'nightly-report', 'done'),
(2, 'billing, retry job', 'done'),
(3, 'say "hi"', 'done')
) AS t(id, title, status)
WHERE status = 'done'
ORDER BY id
) TO STDOUT WITH (FORMAT csv, HEADER true);

Interactive Tools for This Topic