My boss ask me export some data from database for him to do statistic report. PostgreSQL provided easy and useful export feature to do it. Here i will demonstrate how to export data or query result from PostgreSQL into a file or csv file.
1) Connect to PostgreSQL with psql command
yongmo@abcdb:~$ psql -p 5433 -U dba dbname
P.S i installed my PostgreSQL in port 5433, so i need to specific port number.
P.S Type \? to view all available command
2) Type \o /home/yongmo/data25000.csv, it will export query result to /home/yongmo/data25000.csv file.
dbname=> \o /home/yongmo/data25000.csv
3) Type query that you want to export
dbname=> select url from urltable where scoreid=1 limit 25000;
4) Done, all query result exported to /home/yongmo/data25000.csv
Here is the full command
yongmo@abcdb:~$ psql -p 5433 -U dba dbname Password for user dba: Welcome to psql 8.2.4 (server 8.3.3), the PostgreSQL interactive terminal. Type: \copyright for distribution terms \h for help with SQL commands \? for help with psql commands \g or terminate with semicolon to execute query \q to quit WARNING: You are connected to a server with major version 8.3, but your psql client is major version 8.2. Some backslash commands, such as \d, might not work properly. dbname=> \o /home/yongmo/data25000.csv dbname=> select url from urltable where scoreid=1 limit 25000; dbname=> \q


