How to export a PostgreSQL table to a CSV file?

How to export a PostgreSQL table to a CSV file?

Code language: SQL (Structured Query Language) (sql) PostgreSQL exports all data from all columns of the persons table to the persons_db.csv file. In some cases, you want to export data from just some columns of a table to a CSV file. To do this, you specify the column names together with table name after COPY keyword.

How to export a table to a CSV file?

Export data from a table to CSV using COPY statement The easiest way to export data of a table to a CSV file is to use COPY statement. For example, if you want to export the data of the persons table to a CSV file named persons_db.csv in the C:tmp folder, you can use the following statement:

How to copy a PostgreSQL table to a file?

In case you have the access to a remote PostgreSQL database server, but you don’t have sufficient privileges to write to a file on it, you can use the PostgreSQL built-in command \\copy. The \\copy command basically runs the COPY statement above.

How do I copy a CSV file to PSQL?

In psql there are two different commands. The basic usage of the COPY command is as follows: Replace db_name with the actual name of your database and the /path/to/destination with the actual location you want to store the .CSV file in.

How to create a JSON dump from PostgreSQL?

We can do this with ease right from Postgres using the \\g meta-command in place of the semicolon. On its own, it will execute the query just as ; would. However, if followed by a filename, the result of the query will be written to that file. The output will now be in the specified file.

How to export PostgreSQL table as JSON-database?

And using REGEXP_REPLACE thus (note the cast ::TEXT) removes the excess blackslashes. (p.s. As for @Zoltán ‘s comment – this may be a version thing – unable to reproduce!). If you’re using psql then there is no reason to use \\COPY at all.

How is data stored in a PostgreSQL database?

Data in a Postgres database is always in a tabular form. It is stored that way, the results come back that way, even something as simple as select 1; is presented as a table. We want to transition from a tabular result to a JSON one. Postgres has a json_agg function which will do most of the heavy lifting here.

What kind of data type is PostgreSQL 9.4?

PostgreSQL 9.4 introduced very powerful data type called JSON data type. It also introduced a variety of new operators and functions related to JSON data type. This is one of the interesting topics for us and I have recently published a series of articles on PostgreSQL JSON Data type. PostgreSQL 9.4: The JSON data type is Awesome (Part 1/3).