Code Reference

Connect with psql

Postgres · Reference cheat sheet

Connect with psql

Postgres · Reference cheat sheet


📋 Overview

psql is the primary admin CLI: run SQL, inspect catalogs with meta-commands, and script automation with variables and \copy.

🔧 Core concepts

Connection formExample
URLpostgres://user:pass@host:5432/db
Flagspsql -h host -U user -d db
.pgpassPassword file for non-interactive auth
PG* envPGHOST, PGUSER, PGDATABASE
Meta-commandPurpose
\lList databases
\c dbConnect to db
\dtList tables
\d tableDescribe table
\duList roles
\xExpanded display toggle
\timingShow query time
\qQuit

💡 Examples

Connect and list tables:

psql -h 127.0.0.1 -U app -d app
\dt
\d users

Run file / one-shot:

psql "$DATABASE_URL" -f migrate.sql
psql "$DATABASE_URL" -c "SELECT now();"

CSV copy out:

\copy (SELECT id, email FROM users) TO 'users.csv' CSV HEADER

⚠️ Pitfalls

  • Passwords on the command line leak via process lists — prefer .pgpass or env URL carefully.
  • \d shows one schema search_path view — check \dn / qualify schema names.
  • Interactive transactions left open (BEGIN without COMMIT) block others.

On this page