What it is
psql is the interactive terminal for PostgreSQL, used for running SQL commands, managing databases, and inspecting server state.
Installation
Linux (Debian/Ubuntu):
sudo apt update
sudo apt install postgresql-client
Linux (Fedora/CentOS/RHEL):
sudo dnf install postgresql
# or
sudo yum install postgresql
macOS (Homebrew):
brew update
brew install postgresql
Windows:
Download the installer from the PostgreSQL website and follow the instructions. The psql executable will be added to your system’s PATH.
Core Concepts
- Database: A collection of schemas.
- Schema: A namespace within a database that contains tables, functions, and other objects. The
publicschema is the default. - Table: A collection of related data held in rows and columns.
- Meta-commands: Commands starting with a backslash (
\) thatpsqlinterprets directly, not as SQL. They are used for interacting withpsqlitself and the PostgreSQL server.
Commands / Usage
Connecting to a Database
-
Connect to the default database (
postgres) as the default user (postgres):psqlConnects to
postgres://postgres@localhost:5432/postgres -
Connect to a specific database as the default user:
psql mydatabaseConnects to
postgres://postgres@localhost:5432/mydatabase -
Connect as a specific user to a specific database:
psql -U myuser -d mydatabaseConnects to
postgres://myuser@localhost:5432/mydatabase -
Connect to a specific host and port:
psql -h db.example.com -p 5433 -U myuser -d mydatabaseConnects to
postgres://myuser@db.example.com:5433/mydatabase -
Connect using a connection string (URI):
psql postgresql://myuser:mypassword@db.example.com:5432/mydatabaseConnects to the specified database using the provided credentials.
Executing SQL Commands
-
Execute a single SQL command and exit:
psql -c "SELECT version();"Prints the PostgreSQL version and exits.
-
Execute multiple SQL commands from a file:
psql -f /path/to/your/script.sqlRuns all SQL commands found in
script.sql. -
Execute SQL commands interactively (default):
psql mydatabaseOpens an interactive prompt where you can type SQL commands.
Inspecting Database Objects
-
List all databases:
\lLists all databases on the server.
-
List all schemas in the current database:
\dnLists all schemas in the connected database.
-
List all tables in the current database:
\dtLists tables in the connected database.
-
List all tables in a specific schema:
\dt pg_catalog.*Lists tables in the
pg_catalogschema. -
List all tables, views, and sequences:
\dt+ \dv+ \ds+Lists tables, views, or sequences with additional information (size, description).
-
Describe a table’s columns and types:
\d mytableShows the columns, data types, and constraints of
mytable. -
Describe a table’s columns, types, and indices:
\d+ mytableShows detailed information about
mytable, including indices and storage parameters. -
List all functions:
\dfLists all functions.
-
List all views:
\dvLists all views.
-
List all sequences:
\dsLists all sequences.
-
List all extensions:
\dxLists all installed extensions.
-
List all users (roles):
\duLists all roles and their privileges.
Controlling psql Behavior
-
Set the output format to aligned table (default):
psql --pset=format=aligned -
Set the output format to unaligned (CSV-like):
psql --pset=format=unaligned -
Set the output format to HTML:
psql --pset=format=html -
Set the output format to LaTeX:
psql --pset=format=latex -
Turn off the header in query results:
psql --pset=no_header -
Turn off the footer (row count) in query results:
psql --pset=no_footer -
Set the timing of commands to be shown:
psql --pset=timing=on -
Set the prompt:
psql --set prompt1='%n@%m:%5/ %x> 'Sets the primary prompt to show user, host, database, and transaction status.
-
Ignore case for meta-commands:
psql --set IGNORECASE=on -
Turn on automatic saving of command history:
psql --set HISTSIZE=1000 --set HISTFILE=~/.psql_history -
Execute commands from standard input without entering interactive mode:
echo "SELECT * FROM users;" | psql -d mydatabase
Other Useful Meta-Commands
-
Show the current connection information:
\conninfo -
Show the current database and user:
\c(Without arguments, shows current connection info. With arguments, switches connection.)
-
Switch to a different database:
\c newdatabase -
Switch to a different user and database:
\c -U newuser -d newdatabase -
Show the contents of a file:
\i /path/to/another/script.sql(Similar to
-f, but can be used within an interactive session.) -
Edit the current query buffer with an external editor:
\eOpens the current query in your default editor (
$EDITORenvironment variable). -
Show the last executed query:
\qhistory -
Show help on meta-commands:
\? -
Show help on SQL commands:
\h SELECT -
Exit
psql:\q
Common Patterns
-
Exporting data to CSV:
psql -d mydatabase -U myuser -c "COPY mytable TO STDOUT WITH CSV HEADER;" > mytable_export.csvExports
mytabletomytable_export.csvin CSV format with headers. -
Importing data from CSV:
psql -d mydatabase -U myuser -c "COPY mytable FROM STDIN WITH CSV HEADER;" < mytable_import.csvImports data from
mytable_import.csvintomytable. -
Running a script and exiting:
psql -h localhost -U postgres -d mydatabase -f /path/to/setup.sqlConnects to
mydatabaseand executes all commands insetup.sql. -
Piping SQL query output directly to another command:
psql -d mydatabase -t -c "SELECT email FROM users WHERE active = TRUE;" | grep "@example.com"Gets active user emails and filters for those with
@example.com.-tturns off headers and footers for cleaner output. -
Executing a query and getting just the value:
psql -d mydatabase -t -A -c "SELECT COUNT(*) FROM orders WHERE status = 'pending';"Returns only the count, without any formatting.
-Ais for unaligned output. -
Checking the PostgreSQL version on a remote server:
psql -h db.example.com -U myuser -c "SELECT version();" -
Creating a new database:
psql -U postgres -c "CREATE DATABASE new_db_name;" -
Dropping a database:
psql -U postgres -c "DROP DATABASE old_db_name;"
Gotchas
- Meta-commands vs. SQL: Remember that commands starting with
\arepsqlmeta-commands and are not sent to the server as SQL. SQL commands must end with a semicolon (;) forpsqlto execute them. - Quoting: When passing arguments to meta-commands (like table names or schema names), they often need to be quoted if they contain spaces or are keywords. Double quotes (
") are standard SQL quoting. - Connection Defaults: If you don’t specify a host, port, user, or database,
psqluses defaults:localhost,5432, the current OS user, and a database with the same name as the current OS user. COPYPermissions: TheCOPYcommand (used for import/export) typically requires superuser privileges or membership in thepg_read_server_filesorpg_write_server_filesroles for server-side file operations. For client-sideCOPY ... TO STDOUTorCOPY ... FROM STDIN, these restrictions are usually relaxed.\ivs.-f:-fexecutes a script file whenpsqlstarts.\iexecutes a script file from within an activepsqlsession.- Encoding Issues: If you encounter garbled text, ensure your client’s locale and
psql’s encoding settings match the database encoding. You can setPGCLIENTENCODING=UTF8or usepsql --set client_encoding=UTF8.