Sub topic 4
Starting psql
This chapter covers how to launch psql, what happens when it starts, and how to run your first statement. It assumes you can use a terminal and that PostgreSQL is installed with a running server, which the previous chapters covered. It also assumes you know what a database and a table are.
What psql is
psql is the interactive terminal client that ships with PostgreSQL. It opens a connection to a server, reads what you type, sends SQL to the server, and prints the results. It also has its own commands, called meta-commands, which start with a backslash. The server never sees meta-commands. psql handles them itself.
The client and the server are separate programs. You can run psql on one machine and connect to a server on another. Because of this, a working psql does not prove a server is running, and a running server does not prove psql is on your path.
Check the client and the server
Before connecting, confirm that both pieces are available. The first command prints the client version. pg_isready asks the server on the default host and port whether it accepts connections.
psql --version
pg_isreadypsql --version prints something like psql (PostgreSQL) 16.4. If your shell says the command is not found, the client's bin directory is not on your PATH. Reinstalling is rarely needed. Add the directory to PATH or call psql by its full path.
pg_isready prints a status and sets an exit code:
| Exit code | Meaning |
|---|---|
| 0 | The server is accepting connections |
| 1 | The server is rejecting connections, for example while starting up |
| 2 | The server did not respond |
| 3 | No attempt was made, usually because of invalid parameters |
Exit code 2 usually means the server is stopped or you are checking the wrong host or port.
Your first connection
The full form of the command names the host, port, and user.
psql -h localhost -p 5432 -U postgresEach option sets one connection parameter:
-his the host name or address of the server.-pis the TCP port. PostgreSQL listens on 5432 by default.-Uis the role (user) to log in as.
If you do not give a database name, psql connects to a database with the same name as the user. Here that is postgres. You can name a database as a final argument, for example psql -h localhost -U postgres postgres. Chapter five covers these parameters in detail. This chapter only needs enough of them to get a session open.
If the server asks for a password, type it. The characters do not echo to the screen. This is normal.
What the prompt tells you
After a successful login you see a banner and a prompt:
psql (16.4)
Type "help" for help.
postgres=#The prompt shows the current database name followed by a symbol.
| Prompt | Meaning |
|---|---|
| `postgres=#` | Connected to database `postgres` as a superuser |
| `postgres=>` | Connected as a regular, non-superuser role |
| `postgres-#` | The statement continues on another line, so `psql` is waiting for more input |
| `postgres'#` | You opened a single quote and have not closed it |
The # versus > distinction is a quick way to see whether your role has superuser rights. The continuation prompts are a common source of confusion, which we return to below.
Running your first query
Type a statement and end it with a semicolon. The semicolon tells psql the statement is complete and ready to send.
SELECT version();The server returns one row with one column, which holds its version string. psql draws it as a table with a header and a row count:
version
-----------------------------------------------------------
PostgreSQL 16.4 on x86_64-pc-linux-gnu, compiled by gcc...
(1 row)This confirms three things at once. The network path works, authentication succeeded, and the server can parse and run SQL. The version string also tells you the server version, which can differ from the client version printed by psql --version. A newer client can talk to an older server, and the reverse usually works for ordinary SQL. The banner prints a warning when the major versions differ, because some meta-commands may then show incomplete information.
Multi-line input and the semicolon
psql does not send anything until it sees a semicolon at the end of a statement. You can split a statement over several lines, and the prompt changes to a continuation prompt while it waits.
SELECT
1 + 1
AS two;If you press Enter after SELECT version() without a semicolon, nothing happens except a new prompt such as postgres-#. Type ; on the next line to finish it.
If you open a quote and forget to close it, the prompt changes to postgres'#. Typing a semicolon will not help, because the semicolon is now inside the string. Close the quote first, or press Ctrl+C to discard the partial statement and return to a fresh prompt. Ctrl+C at the prompt clears the input buffer. It does not close the session.
Useful ways to start psql
You do not have to connect with separate options. These forms all connect to the same place.
psql "host=localhost port=5432 user=postgres dbname=postgres"
psql postgresql://postgres@localhost:5432/postgres
psql -h localhost -p 5432 -U postgres -d postgresThe first is a key-value connection string. The second is a URI. The third uses the explicit database option -d. Use whichever reads best in your scripts. URIs are convenient for copying between tools, but special characters in a password must be percent-encoded there, so key-value strings are often easier to get right.
Environment variables and passwords
When an option is missing, psql falls back to environment variables. The most common are PGHOST, PGPORT, PGUSER, and PGDATABASE. They let you shorten the command:
export PGHOST=localhost
export PGPORT=5432
export PGUSER=postgres
psqlAvoid putting a password in PGPASSWORD on shared machines, because other processes can sometimes read environment variables. PostgreSQL supports a ~/.pgpass file for stored passwords instead. On Linux and macOS, that file must not be readable by group or others (permissions 0600), or psql ignores it. On Windows the equivalent file is %APPDATA%\postgresql\pgpass.conf.
Running a single command
The -c option runs one command and exits, without starting an interactive session. This is useful in scripts and for quick checks.
psql -h localhost -U postgres -c "SELECT now();"The -f option runs a file of SQL instead. Both are non-interactive. If the file or command fails, psql normally still exits with code 0 for errors inside a multi-statement script unless you set the variable ON_ERROR_STOP:
psql -h localhost -U postgres -v ON_ERROR_STOP=1 -f setup.sqlWith ON_ERROR_STOP=1, psql stops at the first error and exits with a non-zero code, which is what you want in automation.
Leaving psql
Leave the session with the quit meta-command or Ctrl+D on an empty line.
\qThe next chapters use more meta-commands. For now, remember two: \q to quit and \? to list all of them. Typing help at the prompt shows a short orientation, and \h SELECT shows the syntax of an SQL command.
Common startup problems
Most failures here come from a handful of causes.
| Message | Likely cause | First thing to try |
|---|---|---|
| `psql: command not found` | Client not on `PATH` | Add the install `bin` directory to `PATH` |
| `connection refused` | Server stopped, or wrong host or port | Run `pg_isready` and check the port |
| `password authentication failed` | Wrong password or wrong role | Retry with the correct role and password |
| `role "name" does not exist` | The `-U` value is not a role in this cluster | Check the spelling, or use `postgres` |
| `database "name" does not exist` | The default database name matches your user name and has not been created | Pass `-d postgres` explicitly |
The last row catches many beginners. On Linux and macOS, running plain psql with no options uses your operating system user name as both the role and the database name. If no such role or database exists, the login fails even though the server is healthy. Naming the role and database explicitly avoids this.
Exercises
Exercise
You run psql -h localhost -U postgres and the prompt shows postgres-# after you type SELECT version() and press Enter. What happened, and how do you finish the statement?
Show answer
You left out the semicolon, so psql is waiting for more input and treats the next line as a continuation. Type ; on the next line and press Enter to send the statement.
Exercise
You want a script to run setup.sql and stop with a non-zero exit code if any statement fails. Write the command.
Show answer
psql -h localhost -U postgres -v ONERRORSTOP=1 -f setup.sql
Exercise
Your prompt reads postgres=> instead of postgres=#. What does that tell you about your role?
Show answer
The role is not a superuser. The # symbol marks a superuser session, and > marks a regular role.