From 971e5bada57ec2eff59ff6d3cbda8bc7b42db5ee Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 13 Nov 2015 19:00:56 -0600 Subject: [PATCH] Add Export Query Results To A CSV as a postgres til. --- README.md | 1 + postgres/export-query-results-to-a-csv.md | 31 +++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 postgres/export-query-results-to-a-csv.md diff --git a/README.md b/README.md index 63f89ce..5c72b41 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [Default Schema](postgres/default-schema.md) - [Defining Arrays](postgres/defining-arrays.md) - [Edit Existing Functions](postgres/edit-existing-functions.md) +- [Export Query Results To A CSV](postgres/export-query-results-to-a-csv.md) - [Extracting Nested JSON Data](postgres/extracting-nested-json-data.md) - [Find The Data Directory](postgres/find-the-data-directory.md) - [Fizzbuzz With Common Table Expressions](postgres/fizzbuzz-with-common-table-expressions.md) diff --git a/postgres/export-query-results-to-a-csv.md b/postgres/export-query-results-to-a-csv.md new file mode 100644 index 0000000..1d9fb6d --- /dev/null +++ b/postgres/export-query-results-to-a-csv.md @@ -0,0 +1,31 @@ +# Export Query Results To A CSV + +Digging through the results of queries in Postgres's `psql` is great if you +are a programmer, but eventually someone without the skills or access may +need to check out that data. Exporting the results of a query to CSV is a +friendly way to share said results because most people will have a program +on their computer that can read a CSV file. + +For example, exporting all your pokemon to `/tmp/pokemon_dump.csv` can be +accomplished with: + +```sql +copy (select * from pokemons) to '/tmp/pokemon_dump.csv' csv; +``` + +Because we are grabbing the entire table, we can just specify the table name +instead of using a subquery: + + +```sql +copy pokemons to '/tmp/pokemon_dump.csv' csv; +``` + +Include the column names as headers to the CSV file with the `header` +keyword: + +```sql +copy (select * from pokemons) to '/tmp/pokemon_dump.csv' csv header; +``` + +[source](http://stackoverflow.com/questions/1120109/export-postgres-table-to-csv-file-with-headings)