psql Command-Line Client
Connect to PostgreSQL Databases
The psql command is the interactive terminal for
PostgreSQL, allowing you to connect to databases, execute SQL
queries, and manage your database instances directly from the
command line. It's an essential tool for developers and database
administrators working with PostgreSQL.
Basic Connection and Usage
To connect to a database on the local machine using the default port (5432) and the current operating system user, simply use:
psql database_name
Advanced Connection Options
For more specific connections, you can specify the host, port, and username. To connect without a password prompt:
psql -h host_address -p port_number -U username database_name
If you need to be prompted for a password:
psql -h host_address -p port_number -U username -W database_name
Executing SQL Commands and Scripts
psql is versatile and can execute single SQL queries or
entire scripts. To execute a single query directly:
psql -c 'SELECT version();' database_name
To run commands from a SQL file:
psql database_name -f your_script.sql
Related PostgreSQL Tools
When working with PostgreSQL, other useful command-line utilities include:
pg_dump: For backing up PostgreSQL databases.-
pg_restore: For restoring PostgreSQL databases from backups. -
pg_top: A utility to monitor PostgreSQL processes.
For more information and resources on PostgreSQL and
psql, explore PostgreSQL cheat sheets and
documentation.