Sub topic 4
Starting `psql`
Assume PostgreSQL is installed, the server is running, and you are comfortable opening a terminal. You should also know the database name, role name, host, and port that you intend to use. This chapter uses a local server on port 5432 and the postgres role.
What `psql` does
psql is PostgreSQL's command-line client. It opens a session with a PostgreSQL server and lets you send SQL statements. The client and server are separate programs:
The psql program sends your commands to the server. The server authenticates you, runs SQL, and sends results back. Installing PostgreSQL usually installs both the server and the psql client, although some systems package them separately.
Check that the client is installed and that the server accepts connections:
psql --version
pg_isreadyThe first command prints the installed psql version. The second checks the default host and port, usually localhost:5432. A successful check reports that the server is accepting connections.
Connect with explicit parameters
Use -h for the host, -p for the port, and -U for the role, which is PostgreSQL's name for a user account:
psql -h localhost -p 5432 -U postgresIf you omit the database name, psql commonly tries to connect to a database with the same name as the role. To choose a database explicitly, add its name as the final argument:
psql -h localhost -p 5432 -U postgres -d postgresThe command may ask for the role's password. On a local development installation, authentication rules may instead use your operating-system account or another local method.
After a successful connection, psql displays a prompt similar to this:
postgres=#The prompt shows the current database. A # often indicates a superuser role. A regular role commonly sees =>.
Run SQL in the session
At the prompt, enter a SQL statement and finish it with a semicolon:
SELECT version();The server returns its version string. This query confirms that the session can send SQL and receive a result.
You can also run a SQL file from your shell:
psql -h localhost -p 5432 -U postgres -d postgres -f setup.sqlThe -f option tells psql to read commands from setup.sql. This is useful when a set of statements is too long to type interactively.
SQL commands and `psql` meta-commands
Commands beginning with a backslash are handled by psql, not by the PostgreSQL SQL engine. They are called meta-commands. For example, \q exits the session:
\qThe prompt changes when you connect to another database, and \conninfo displays the current connection details:
\conninfoUse \? to list available meta-commands and \h SELECT to view help for the SQL SELECT command.
Exercise
Which command connects to database library on host localhost, port 5432, using role reader?
Show answer
psql -h localhost -p 5432 -U reader -d library