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
- Connect:
psql -U username -d database -h localhost - List tables:
\dt - Describe a table:
\d table_name - Run a script:
\i /path/to/script.sql - Save output to a file:
\o output.txt
Tips
- Use
\xto toggle expanded display for wide tables. - Set
PSQL_HISTORYand.psqlrcto 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
PGPASSWORDenvironment variables or.pgpassfiles.r