PostgreSQL and CSVs

PostgreSQL is a popular, open source, relational database used by many websites and applications. PostgreSQL provides tools for importing and exporting CSVs.


Getting CSVs from PostgreSQL is easy

\COPY my_table TO '/path/to/new_file.csv' CSV HEADER;
Connect to PostgreSQL
To connect to a PostgreSQL database from the command line psql -h host_name -p port_number -U username -d database_name
psql -h my_cluster.rds.amazonaws.com -p 5432 -U admin -d my_database
Or psql postgresql://username@host_name:port_number/database_name
psql postgresql://admin@my_cluster.rds.amazonaws.com:5432/my_database

To run commands directly from the shell, use psql's -c flag.

psql -c "\COPY my_table TO '/path/to/new_file.csv' CSV HEADER";
Copy vs \Copy
There are two commands for working with CSVs, COPY and \COPY. They're almost identical, but you almost always want to use \COPY. COPY my_table TO '/path/to/new_file.csv' CSV HEADER;
\COPY my_table TO '/path/to/new_file.csv' CSV HEADER;

1. COPY will create the CSV file on the database's machine, while \COPY will create the file on the client (your) machine.

2. Only superusers can use COPY, but almost anyone can use \COPY.

Export to CSV Examples
COPY my_table TO '/path/to/new_file.csv' CSV HEADER; Export the table my_table to a file called new_file.csv with , as the delimiter, and include a HEADER row.
COPY my_table TO '/path/to/new_file.csv' CSV DELIMITER ',' QUOTE '"' HEADER; Export the table my_table to a file called new_file.csv with a HEADER row and

Delimiter: ,

Quote Character: "

Delimiters must be one character. To use Tab as a delimiter, type Ctrl+v then Tab.