How to use the psql command line tool

· Category: SQL & Databases

Short answer

psql is the interactive terminal for PostgreSQL. It supports SQL execution, meta-commands, scripting, and output formatting.

Steps

  1. Connect: psql -U username -d database -h localhost
  2. List tables: \dt
  3. Describe a table: \d table_name
  4. Run a script: \i /path/to/script.sql
  5. Save output to a file: \o output.txt

Tips

  • Use \x to toggle expanded display for wide tables.
  • Set PSQL_HISTORY and .psqlrc to customize defaults and preserve history.

Common issues

  • Forgetting the semicolon at the end of a SQL statement causes psql to wait for more input.
  • Special characters in passwords may require PGPASSWORD environment variables or .pgpass files.r