psql(1)
psql is an interactive terminal for PostgreSQL that lets you execute SQL queries and manage databases.
Synopsis
psql [OPTION]... [DBNAME [USERNAME]]Description
psql is the PostgreSQL interactive query terminal. It allows you to type SQL commands interactively, issue them to PostgreSQL, and see the results. You can also save queries to files, use variables, and execute scripts. psql supports command-line editing and a command history.
Connection parameters can be specified via command-line options, environment variables (like PGHOST, PGUSER, PGPASSWORD), or a .pgpass file for password authentication. If no database is specified, it defaults to a database with the same name as the current user.
Common options
| Flag | What it does |
|---|---|
-h, --host=HOSTNAME | database server host or socket directory (default: localhost) |
-p, --port=PORT | database server port (default: 5432) |
-U, --username=USERNAME | database user name (default: current OS user) |
-d, --dbname=DBNAME | database name to connect to |
-W, --password | force password prompt (useful when password is in .pgpass) |
-c, --command=COMMAND | run only this SQL command and exit |
-f, --file=FILENAME | execute commands from file, then exit |
-l, --list | list all available databases and exit |
-A, --no-align | unaligned output mode (fields separated by delimiter) |
-H, --html | HTML table output mode |
-t, --tuples-only | print rows only, no column headers or summary |
-x, --expanded | expanded output (one column per line) |
Examples
Connect to 'mydb' database as 'postgres' user on localhost
psql -U postgres -d mydbConnect to a remote PostgreSQL server at 192.168.1.50 as admin user
psql -h 192.168.1.50 -U admin -d productionExecute a single SQL query and exit without entering interactive mode
psql -c "SELECT * FROM users;" mydbRun SQL commands from a file against 'mydb' database
psql -f /path/to/script.sql mydbList all databases on the local PostgreSQL server
psql -lOutput query results in unaligned, tuples-only format (useful for scripting)
psql -d mydb -A -t -c "SELECT name, email FROM users;"Connect as postgres user and prompt for password
psql -U postgres -WDisplay help information and exit
psql --help