How can I dump all tables to CSV for a PostgreSQL schema?

Here's a shell script that can do what you want:

SCHEMA="myschema"
DB="mydb"

psql -Atc "select tablename from pg_tables where schemaname='$SCHEMA'" $DB |\
  while read TBL; do
    psql -c "COPY $SCHEMA.$TBL TO STDOUT WITH CSV" $DB > $TBL.csv
  done

Make sure you set the DB and SCHEMA variables to your particular database and schema.

The wrapping psql command uses the A and t flags to make a list of tables from the string passed to the c command.


If you need to export all schemas, here's the script

PGDATABASE="db"
PGUSER="user"

psql -Atc "select schema_name from information_schema.schemata" |\
    while read SCHEMA; do
    if [[ "$SCHEMA" != "pg_catalog" && "$SCHEMA" != "information_schema" ]]; then
        psql -Atc "select tablename from pg_tables where schemaname='$SCHEMA'" |\
            while read TBL; do
                psql -c "COPY $SCHEMA.$TBL TO STDOUT WITH CSV DELIMITER ';' HEADER ENCODING 'UTF-8'" > $SCHEMA.$TBL.csv
            done
    fi
    done