Exporting data from PostgreSQL to CSV file is a common task in data analysis and further processing. This article explores two ways to achieve this using PL/pgSQL procedures:
This method utilizes PostgreSQL’s built-in COPY command. It allows you to write SQL result sets directly to a file on the server. Example:
<code>COPY (SELECT * FROM foo) TO '/tmp/test.csv' WITH CSV DELIMITER ',' HEADER;</code>
Advantages:
Disadvantages:
You can use COPY TO STDOUT to retrieve the data and handle the file writing in the client application instead of using COPY on the server. Example in psql:
<code>\copy (SELECT * FROM foo) TO '/tmp/test.csv' WITH CSV DELIMITER ',' HEADER</code>
Advantages:
Disadvantages:
If you choose a server-side approach, be sure to implement appropriate security measures, such as:
The above is the detailed content of How to Efficiently Export PL/pgSQL Query Results to a CSV File in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!