Home >Database >Mysql Tutorial >How to Export PL/pgSQL Query Results to a CSV File in PostgreSQL?
PostgreSQL's PL/pgSQL procedural language allows for powerful database extensions. This guide details two methods for saving PL/pgSQL query results to a CSV file.
Method 1: Server-Side Export using COPY
The most efficient server-side approach utilizes PostgreSQL's COPY
command. A command like this:
<code class="language-sql">COPY (SELECT * FROM foo) TO '/tmp/test.csv' WITH CSV DELIMITER ',' HEADER;</code>
exports data from the "foo" table to a CSV file on the server. Crucially, this requires appropriate server-side permissions. Best practice involves creating a dedicated function with the SECURITY DEFINER
option to manage these permissions securely.
Method 2: Client-Side Export using COPY TO STDOUT
Alternatively, you can handle CSV export on the client-side using the COPY TO STDOUT
command within the psql
command-line client. The copy
meta-command facilitates this:
<code class="language-sql">\copy (SELECT * FROM foo) TO '/tmp/test.csv' WITH CSV DELIMITER ',' HEADER</code>
Note that copy
is a meta-command, not a standard SQL command, so a terminating semicolon (;
) is unnecessary.
Security Considerations (Server-Side):
The server-side approach necessitates careful security planning:
Considerations for Client-Side Approach:
When using the client-side method:
pg_copy_from
and pg_copy_to
might be suboptimal. Consider alternative, more efficient methods.The above is the detailed content of How to Export PL/pgSQL Query Results to a CSV File in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!