Sub topic 1
What PostgreSQL is and how clients talk to it
Prerequisites
You should be comfortable typing commands in a terminal and know that a database stores data in tables. You also need permission to install software on your computer. This chapter assumes you can read a short error message and change a command when something fails.
How PostgreSQL works
PostgreSQL is an open-source relational database. It stores data in tables and answers queries written in SQL, the standard language for databases. It runs as a server process that listens for connections on a network port, 5432 by default. Clients, such as the psql command-line tool or an application, open a connection to that port, send SQL text, and read the results.
Installing PostgreSQL
Install PostgreSQL with your system's package manager or installer:
- Debian or Ubuntu Linux:
sudo apt install postgresql postgresql-client - macOS with Homebrew:
brew install postgresql@16 - Windows: the official installer from postgresql.org
Then confirm the client version:
psql --versionThe output looks like psql (PostgreSQL) 16.x. The exact number depends on your installation.
Checking that the server is running
The client and the server are separate programs. Installing one does not start the other. The pg_isready tool checks whether a server accepts connections:
pg_isready -h localhost -p 5432A reply ending in "accepting connections" means the server is ready. "no response" means the server is stopped, or the host or port is wrong.
Starting psql and choosing what it connects to
psql needs four values to connect: host, port, user, and database.
| Parameter | Flag | Default when omitted | Purpose |
|---|---|---|---|
| Host | -h | The local machine | Machine that runs the server |
| Port | -p | 5432 | Network port the server listens on |
| User | -U | Your operating system login name | PostgreSQL role to authenticate as |
| Database | -d | Same as the user name | Database to open |
Connect with explicit values:
psql -h localhost -p 5432 -U postgres -d postgresOnce connected, the prompt shows postgres=#. Run a test query:
SELECT version();> Note: the default database name equals the user name. Running psql -U alice without -d tries to open a database named alice, which may not exist.
Exercise
Which command checks whether a server accepts connections on localhost, port 5432?
Show answer
pg_isready -h localhost -p 5432