Tools › Cheat sheets › Web Servers & Databases › PostgreSQL
🐘

PostgreSQL cheat sheet

Commands for the psql client and PostgreSQL tools. Inside psql, backslash commands are meta-commands handled by the client; SQL statements end with a semicolon.

Click any command to copy it.

Connect

CommandWhat it does
psql -U user -d database -h hostConnect to a database.
sudo -u postgres psqlConnect as the postgres superuser locally.
psql "postgresql://user:pass@host:5432/db"Connect using a connection URI.
\conninfoShow the current connection details.
\qQuit psql.

Explore

CommandWhat it does
\lList databases.
\c dbnameConnect to another database.
\dtList tables (add + for sizes).
\d tablenameDescribe a table's columns, indexes and constraints.
\duList roles.
\dnList schemas.
\dfList functions.
\xToggle expanded (vertical) output for wide rows.
\timingToggle query timing.

Run files and export

CommandWhat it does
psql -d db -f script.sqlRun a SQL file.
\i script.sqlRun a SQL file from inside psql.
\copy tablename TO 'out.csv' CSV HEADERExport a table to CSV on the client.
\copy tablename FROM 'in.csv' CSV HEADERImport a CSV file into a table.

Backup and restore

CommandWhat it does
pg_dump -U user db > db.sqlDump a database as plain SQL.
pg_dump -Fc db -f db.dumpDump in the compressed custom format.
psql -U user -d db < db.sqlRestore a plain SQL dump.
pg_restore -d db --clean db.dumpDestructive: Restore a custom-format dump, dropping existing objects first.
pg_dumpall > all.sqlDump every database and the roles.

Roles and databases

CommandWhat it does
CREATE DATABASE appdb;Create a database.
CREATE USER appuser WITH PASSWORD 'secret';Create a login role.
GRANT ALL PRIVILEGES ON DATABASE appdb TO appuser;Allow a role full access to a database.
\password appuserChange a role's password without exposing it in history.
DROP DATABASE appdb;Destructive: Permanently delete a database.

Diagnostics

CommandWhat it does
SELECT pg_size_pretty(pg_database_size('db'));Database size in a readable form.
SELECT * FROM pg_stat_activity;Current connections and their queries.
SELECT pg_terminate_backend(PID);Disconnect a session by process ID.
EXPLAIN ANALYZE SELECT ...;Run a query and show its real execution plan.
VACUUM ANALYZE tablename;Reclaim space and refresh planner statistics.

Frequently asked questions

How do I list all tables?

Inside psql run \dt, or \dt *.* to include every schema.

How do I avoid putting a password on the command line?

Use a ~/.pgpass file (chmod 600) or the PGPASSWORD environment variable for scripts, or \password inside psql.

More Web Servers & Databases cheat sheets

🚦 nginx🐬 MySQL / MariaDB🔴 RedisAll Web Servers & Databases cheat sheets →
Copied to clipboard