$linuxjunkies
>

psql(1)

psql is an interactive terminal for PostgreSQL that lets you execute SQL queries and manage databases.

UbuntuDebianFedoraArch

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

FlagWhat it does
-h, --host=HOSTNAMEdatabase server host or socket directory (default: localhost)
-p, --port=PORTdatabase server port (default: 5432)
-U, --username=USERNAMEdatabase user name (default: current OS user)
-d, --dbname=DBNAMEdatabase name to connect to
-W, --passwordforce password prompt (useful when password is in .pgpass)
-c, --command=COMMANDrun only this SQL command and exit
-f, --file=FILENAMEexecute commands from file, then exit
-l, --listlist all available databases and exit
-A, --no-alignunaligned output mode (fields separated by delimiter)
-H, --htmlHTML table output mode
-t, --tuples-onlyprint rows only, no column headers or summary
-x, --expandedexpanded output (one column per line)

Examples

Connect to 'mydb' database as 'postgres' user on localhost

psql -U postgres -d mydb

Connect to a remote PostgreSQL server at 192.168.1.50 as admin user

psql -h 192.168.1.50 -U admin -d production

Execute a single SQL query and exit without entering interactive mode

psql -c "SELECT * FROM users;" mydb

Run SQL commands from a file against 'mydb' database

psql -f /path/to/script.sql mydb

List all databases on the local PostgreSQL server

psql -l

Output 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 -W

Display help information and exit

psql --help

Related commands