Skip to content

Basic Usage

The pg command follows a simple pattern: pg <command> [subcommand] [options]

Command Structure

pg <command> [subcommand] [pg-options] [tool-options]
  • Command: What category of operation (query, dump, create, etc.)
  • Subcommand: Specific operation within that category (optional - some commands like query don't need one)
  • Pg options: How to connect (-s, -h, -u, etc.) or dry-run or verbosity - Must come before tool options
  • Tool options: Passed directly to the underlying PostgreSQL tool

Option Order Matters

Connection options (-s, -h, -u, -d, -p, -c) must come before tool-specific options. Once pg encounters an unknown flag, it passes everything remaining to the PostgreSQL tool.

Subcommands are Optional

Some commands work standalone (like pg query), while others require subcommands (like pg dump db). Use pg help to see which commands need subcommands.

Essential Commands

Query Database

pg query -s production
pg query -h localhost -u admin -d myapp

Export Data (Logical)

pg dump db -s production dump.sql # or pg export db production dump.sql
pg dump all -s production cluster-dump.sql # or pg export -s production cluster-dump.sql

Import Data

pg dump restore -s staging dump.sql # or pg import -s staging dump.sql

Database Management

pg create db -s development -d newapp
pg drop db -s development -d oldapp

User Management

pg create user -s production john
pg drop user -s production john

Maintenance

pg maintain vacuum -s production
pg maintain reindex -s production

Server Status

pg info ready -s production # or pg ready -s production
pg info config

Connection Priority

pg uses PostgreSQL's standard connection resolution:

  1. Service file (-s servicename) - Recommended
  2. Connection string (-c "host=... user=...")
  3. Individual flags (-h host -u user -d database)
  4. Environment variables (PGHOST, PGUSER, etc.)

Dry Run Mode

Test commands without executing:

pg dump db -s production --pg-dry-run dump.sql # or pg export db -s production --pg-dry-run
# Output: Would execute: pg_dump -d 'service=production' dump.sql

Getting Help

pg help                       # Full pg command list
pg maintain --help            # Shows pg maintain's help
pg create user --help         # Shows createuser's help
pg query --pg-verbose         # Debug connection issues

Next: Learn about Connection Options to master service files and other connection methods.