psql
psql
is a terminal-based front-end to PostgreSQL. It enables you to interact with the PostgreSQL database server using SQL queries and commands.
psql is a powerful, interactive terminal interface for PostgreSQL, enabling database management and SQL query execution.
Related
See Postgres cheatsheet.
Install
See PostgreSQL Documentation for installation instructions.
$ sudo apt-get install postgresql-client
Manpage
NAME
psql - PostgreSQL interactive terminal
SYNOPSIS
psql [OPTIONS] [DBNAME [USERNAME]]
psql [OPTIONS] [-c COMMAND | -f FILE] [DBNAME [USERNAME]]
...
Bash shell usage
Connect to a database
Connect to a PostgreSQL database:
$ psql -d dbname -U username
Import SQL file
Execute commands from a SQL file:
$ psql -d dbname -U username -f filename.sql
PSQL interactive mode usage
List databases
List all available databases:
# \l
Connect to a database from within psql
Switch to another database from within psql
:
# \c dbname
List tables
List all tables in the current database:
# \dt
Describe table
Show the structure of a table:
# \d tablename
Execute a SQL query
Execute a SQL query:
# SELECT * FROM tablename;
Quit psql
Exit the psql interface:
# \q
Get help
Show help on psql
commands:
# \?
Show SQL command history
Display the history of executed SQL commands:
# \s
Set output format
Set the output format to aligned, unaligned, or HTML:
# \a # Aligned
# \t # Unaligned
# \H # HTML
Export query results
Export the result of a query to a file:
# \o filename
# SELECT * FROM tablename;
# \o
Edit command in editor
Open the current command in a text editor for modification:
# \e