Exporting PL/pgSQL Output to a CSV File in PostgreSQL
In PostgreSQL, you can save the output of a SELECT query or any result from a PL/pgSQL function to a CSV file. This can be done using the COPY command, which is efficient for exporting query results directly to a file. This guide covers how to save PL/pgSQL output to a CSV file step-by-step.
1. Using the COPY Command for Direct Export
The COPY command can export data directly to a CSV file. You can use it for any query that produces output, including within PL/pgSQL functions.
Syntax:
COPY (SELECT column1, column2 FROM table_name WHERE condition) TO '/path/to/your/file.csv' WITH (FORMAT CSV, HEADER);
Example Code:
-- Export the result of a query to a CSV file
COPY (SELECT id, name, email FROM users WHERE active = true) -- Select data to export
TO '/tmp/active_users.csv' -- Define file path
WITH (FORMAT CSV, HEADER); -- Specify CSV format with header
Explanation:
2. Using psql to Export Query Results to CSV
You can run COPY commands directly within the psql command-line tool to export data to a CSV file without using a PL/pgSQL function.
Example Code:
# Run psql and export data to CSV
psql -U postgres -d your_database -c "\COPY (SELECT * FROM your_table) TO '/path/to/file.csv' CSV HEADER"
Explanation:
3. Using PL/pgSQL Function to Generate CSV Data
You can also use a PL/pgSQL function to generate specific data, and then export the output with COPY.
Example Code:
CREATE OR REPLACE FUNCTION export_active_users_to_csv() RETURNS void AS $$
DECLARE
BEGIN
-- Export query result to a CSV file
PERFORM COPY (SELECT id, name FROM users WHERE active = true) -- Fetch active users
TO '/tmp/active_users.csv' -- Define file path
WITH (FORMAT CSV, HEADER); -- Specify CSV format with header
END;
$$ LANGUAGE plpgsql;
Explanation:
Important Notes
All PostgreSQL Questions, Answers, and Code Snippets Collection.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4