LinuxCommandLibrary

psql

PostgreSQL interactive terminal client

TLDR

Connect to database

$ psql -d [database]
copy
Connect to remote server
$ psql -h [host] -U [user] -d [database]
copy
Execute SQL command
$ psql -c "SELECT * FROM [table]" [database]
copy
Execute SQL file
$ psql -f [script.sql] [database]
copy
List databases
$ psql -l
copy
Interactive mode
$ psql [database]
copy

SYNOPSIS

psql [options] [dbname]

DESCRIPTION

psql is the official interactive terminal for PostgreSQL. It provides a command-line interface for connecting to databases, executing SQL queries, and managing database objects. In interactive mode, it offers features like tab completion, command history, and formatted output for query results.
Beyond interactive use, psql can execute SQL files with -f and run individual commands with -c, making it suitable for scripting and automation. Built-in backslash commands (like \dt for tables, \d for describing objects, and \l for listing databases) provide quick access to database metadata without writing SQL.
Connection parameters can be specified via command-line flags, environment variables (PGHOST, PGUSER, PGDATABASE, PGPORT), or the ~/.pgpass file for password-free authentication.

PARAMETERS

DBNAME

Database name.
-h HOST
Server hostname.
-p PORT
Port number.
-U USER
Username.
-d DBNAME
Database name.
-c COMMAND
Execute command.
-f FILE
Execute file.
-l
List databases.

CONFIGURATION

~/.pgpass

Password file for automatic authentication, containing lines in the format `hostname:port:database:username:password`.
~/.psqlrc
Startup file executed when psql launches, used to set formatting options, custom prompts, and default settings.
PGHOST, PGUSER, PGDATABASE, PGPORT
Environment variables for default connection parameters.

CAVEATS

PostgreSQL specific. Requires server connection.

HISTORY

psql is the official PostgreSQL command-line client.

SEE ALSO

pg_dump(1), createdb(1), mysql(1)

> TERMINAL_GEAR

Curated for the Linux community

Copied to clipboard

> TERMINAL_GEAR

Curated for the Linux community