PostgreSQL CLI Cheat Sheet
Also see PostgreSQL Cheat Sheet.
Backslash Commands π
\?
β Show all the commands\copy
β Similar to SQL copy command but uses local files instead of paths on the server.\e
β Open an editor to write a query. You can append this to the end of a line (without semicolon, see\;
below) to edit the current query.\gdesc
β Show the format of the current queryβs result, without actually executing it.\ef
β Edit a function\ev
β Edit a view\timing
β Show how long each command takes to run\i FILE
β Execute commands in a file\df
β Function detail\dT
β Type detail\;
β Ends a query like a normal semicolon, but psql will not submit the query until it sees an unescaped semicolon. The queries will be executed as a single transaction.
PSQL Variables π
Set these with \set VAR VALUE
.
- AUTOCOMMIT β Set
on
(the default) to commit changes after each statement. Whenoff
or unset, each statement not already in a transaction is implicitly prepended with aBEGIN
statement and then you mustCOMMIT
orEND
to commit the changes. - ECHO_HIDDEN β Set to
on
to echo all queries generated by backslash commands. This can also be done with the-E
command line flag.
Connection Services π
Adding the file ~/pg_service.conf
lets you define connection string presets.
[YOUR_SERVICE_NAME]
host=HOST
port=PORT
dbname=DBNAME
user=USER
Run psql service=YOUR_SERVICE_NAME
to connect to it.
Passwords π
You can add the file ~/.pgpass
to supply the password. Each line has the format HOST:PORT:DBNAME:USER:PASSWORD
. Any of these fields can be *
to use them as a wildcard.
The obvious caveats about writing your passwords in a plaintext file apply, and as with SSH private keys, the files must be accessible only by your user (i.e. chmod 600 ~/.pgpass
).
Thanks for reading! If you have any questions or comments, please send me a note on Twitter. And if you enjoyed this, I also have a newsletter where I send out interesting things I read and the occasional nature photo.