aboutsummaryrefslogtreecommitdiff
path: root/dotfiles/cheat/psql
blob: 2efdcedd34ae1e87a6b7133157f6da21d3a783e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# psql is the PostgreSQL terminal interface. The following commands were tested on version 9.5.
# Connection options:
# -U username (if not specified current OS user is used).
# -p port.
# -h server hostname/address.

# Connect to a specific database:
psql -U postgres -h serverAddress -d dbName

# Get databases on a server:
psql -U postgres -h serverAddress --list

# Execute sql query and save output to file:
psql -U postgres -d dbName -c 'select * from tableName;' -o fileName

# Execute query and get tabular html output:
psql -U postgres -d dbName -H -c 'select * from tableName;'

# Execute query and save resulting rows to csv file
# (if column names in the first row are not needed, remove the word 'header'):
psql -U postgres -d dbName -c 'copy (select * from tableName) to stdout with csv header;' -o fileName.csv

# Read commands from file:
psql -f fileName

# Restore databases from file:
psql -f fileName.backup postgres

# clear tables in db
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;