Skip to content

Instantly share code, notes, and snippets.

@taboularasa
Last active August 29, 2015 13:57
Show Gist options
  • Save taboularasa/9496627 to your computer and use it in GitHub Desktop.
Save taboularasa/9496627 to your computer and use it in GitHub Desktop.
export all tables to CSV

In psql, define the function:

CREATE OR REPLACE FUNCTION db_to_csv(path TEXT) RETURNS void AS $$
declare
  tables RECORD;
  statement TEXT;
begin
  FOR tables IN
    SELECT (table_schema || '.' || table_name) AS schema_table
    FROM information_schema.tables t INNER JOIN information_schema.schemata s
    ON s.schema_name = t.table_schema 
    WHERE t.table_schema NOT IN ('pg_catalog', 'information_schema', 'configuration')
    ORDER BY schema_table
  LOOP
    statement := 'COPY ' || tables.schema_table || ' TO ''' || path || '/' || tables.schema_table || '.csv' ||''' DELIMITER '','' CSV HEADER';
    EXECUTE statement;
  END LOOP;
  return;
end;
$$ LANGUAGE plpgsql;

The function is used as follows:

SELECT db_to_csv('/home/user/dir');

Found on the following SO question: http://stackoverflow.com/questions/17463299/export-database-into-csv-file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment