PostgreSQL CLI Essentials Guide | Generated by AI

Home 2026.02

PostgreSQL offers several command-line utilities, each with extensive options. Here’s a comprehensive guide to the most important ones.

psql (Interactive Terminal)

The psql command is your primary interface for interacting with PostgreSQL databases.

Connection Options:

Output Options:

Behavior Options:

Example:

psql -h localhost -U postgres -d mydb -c "SELECT * FROM users LIMIT 5"

pg_dump (Backup Utility)

Creates backup copies of databases.

General Options:

Output Format:

Selective Dumping:

Compression:

Example:

pg_dump -h localhost -U postgres -d mydb -F c -f mydb_backup.dump

pg_restore (Restore Utility)

Restores databases from backups created by pg_dump.

Connection Options:

Restore Options:

Selective Restore:

Example:

pg_restore -h localhost -U postgres -d mydb -c mydb_backup.dump

createdb / dropdb

Quick database creation and deletion utilities.

createdb Options:

Example:

createdb -h localhost -U postgres -O myuser mynewdb
dropdb -h localhost -U postgres olddb

createuser / dropuser

User management utilities.

createuser Options:

Example:

createuser -h localhost -U postgres -d -P newuser

pg_isready

Checks connection status to PostgreSQL server.

Options:

Example:

pg_isready -h localhost -p 5432

Common Patterns

Connecting to remote database:

psql -h db.example.com -p 5432 -U admin -d production

Creating a compressed backup:

pg_dump -h localhost -U postgres -d mydb -F c -Z 9 -f backup.dump

Dumping just one table:

pg_dump -h localhost -U postgres -d mydb -t users -f users.sql

Restoring to a different database name:

createdb newdb
pg_restore -h localhost -U postgres -d newdb backup.dump

Running SQL from a file:

psql -h localhost -U postgres -d mydb -f schema.sql

Setting environment variables to avoid repetition:

export PGHOST=localhost
export PGPORT=5432
export PGUSER=postgres
export PGDATABASE=mydb

psql  # now connects automatically

Most PostgreSQL utilities also respect PGPASSWORD environment variable, though using a .pgpass file is more secure for production use.


Back Donate