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. Whenoffor unset, each statement not already in a transaction is implicitly prepended with aBEGINstatement and then you mustCOMMITorENDto commit the changes. - ECHO_HIDDEN β Set to
onto echo all queries generated by backslash commands. This can also be done with the-Ecommand 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.