Cheatsheet: PostgreSQL
Last updated 2026-08-25
Connecting
connect to a local database as a user
connect to a remote server, specifying host and port
connect using a connection URI
connect and immediately run one command, then exit
run a .sql file against a database
quit the psql prompt
psql meta-commands
list all databases
connect to a different database
list tables in the current database
describe a table (columns, types, indexes)
list views
list indexes
list users/roles
list schemas
show table sizes
toggle expanded (vertical) output — great for wide rows
show command history
get help on SQL commands
get help on psql meta-commands
Databases and roles
create a database
drop a database
create a role/user with a password that can log in
grant all privileges on a database to a user
make a user a superuser
change a user's password
list roles and their attributes
Tables
create a table
add a column
rename a column
drop a column
drop a table
truncate a table (delete all rows, keep schema)
create an index on a column
Querying
select rows with a filter
upsert a row (insert or update on conflict)
return the inserted/updated row
aggregate with GROUP BY
window function example: running total
explain a query's execution plan
Backup and restore
dump a single database to a SQL file
dump a database in the custom (compressed) format
restore a plain SQL dump
restore a custom-format dump
dump all databases and roles on a server
Server operations
start the server (Homebrew install)
stop the server (Homebrew install)
start/stop the server (systemd install)
show currently running queries
cancel a running query
terminate a connection