Table Of Content
- Prerequisites
- Step 1 — Installing PostgreSQL
- Step 2 — Understanding PostgreSQL Roles and Authentication
- Step 3 — Creating a New Role
- Step 4 — Creating a New Database
- Step 5 — Opening a Prompt With the New Role
- Step 6 — Creating and Deleting Tables
- Step 7 — Adding, Querying, Updating and Deleting Data
- Step 8 — Allowing Remote Connections (Optional)
- Conclusion
Introduction
PostgreSQL (often just Postgres) is an open-source relational database known for its stability, strict SQL compliance and advanced features such as JSON data types, full-text search and extensions. It is the default choice for many modern frameworks and platforms, including Django, Rails, Prisma and Supabase.
In this guide we will install PostgreSQL on Ubuntu, look at how Postgres handles authentication, create a role and database, and practise the basic table operations.
Prerequisites
- A server running Ubuntu 20.04 or 22.04.
- A regular user with
sudoprivileges.
Step 1 — Installing PostgreSQL
PostgreSQL is available in Ubuntu's default repositories. Update the package index and install the postgresql package along with postgresql-contrib, which adds some extra utilities:
sudo apt update
sudo apt install postgresql postgresql-contribThe service starts automatically after installation. Check its status:
sudo systemctl status postgresqlOutput
● postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
Active: active (exited) since Fri 2026-09-05 10:02:14 UTC; 1min 3s ago
Main PID: 5183 (code=exited, status=0/SUCCESS)The active (exited) state is normal: postgresql.service is only a wrapper, the actual server runs as postgresql@14-main.service (the version number may differ on your machine).
If you want a newer PostgreSQL release than the one in Ubuntu's repository, add the official PostgreSQL (PGDG) repository:
sudo sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt update
sudo apt install postgresql-16Step 2 — Understanding PostgreSQL Roles and Authentication
Postgres uses the concept of roles to handle authentication and authorisation. A role can be thought of as a user or a group of users.
By default Postgres uses peer authentication for local connections: if the operating system username matches a Postgres role name, that user can log in without a password.
The installation creates an operating system account called postgres, which corresponds to the default postgres administrative role. There are two ways to use it.
Option 1: switch to the postgres account, then open the prompt:
sudo -i -u postgres
psqlOption 2: run psql directly as the postgres account without switching shells:
sudo -u postgres psqlEither way you land in the PostgreSQL prompt:
Output
psql (14.10 (Ubuntu 14.10-0ubuntu0.22.04.1))
Type "help" for help.
postgres=#To exit the prompt, type:
\qStep 3 — Creating a New Role
Right now only the postgres role exists. It is good practice to create a separate role for each application rather than using the administrative role.
From the postgres account, use createuser with the --interactive flag to be prompted for the options:
sudo -u postgres createuser --interactiveOutput
Enter name of role to add: sammy
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) nAlternatively, create the role with a password from inside psql. You need this if your application connects with a password:
sudo -u postgres psqlCREATE ROLE sammy WITH LOGIN PASSWORD 'password';
ALTER ROLE sammy CREATEDB;Step 4 — Creating a New Database
By default, when a role logs in, Postgres tries to connect to a database with the same name as the role. So create a database matching the role you just made:
sudo -u postgres createdb sammyOr create a database with any name and assign the role as its owner:
CREATE DATABASE myapp OWNER sammy;On PostgreSQL 15 and later, roles no longer have permission to create tables in the default public schema. If you hit permission denied for schema public, grant it:
GRANT ALL ON SCHEMA public TO sammy;Step 5 — Opening a Prompt With the New Role
To authenticate with peer authentication you need an operating system user with the same name as the Postgres role. If it does not exist, create it:
sudo adduser sammyThen switch to that user and open the prompt:
sudo -i -u sammy
psqlTo connect to a database with a different name than the role:
psql -d myappCheck the current connection details:
\conninfoOutput
You are connected to database "sammy" as user "sammy" via socket in "/var/run/postgresql" at port "5432".If you would rather not create an operating system user, connect with a password over TCP instead:
psql -h localhost -U sammy -d myappStep 6 — Creating and Deleting Tables
Now that you know how to connect, let's practise the basics. Create a playground table to store playground equipment:
CREATE TABLE playground (
equip_id serial PRIMARY KEY,
type varchar (50) NOT NULL,
color varchar (25) NOT NULL,
location varchar(25) check (location in ('north', 'south', 'west', 'east', 'northeast', 'southeast', 'southwest', 'northwest')),
install_date date
);What this does:
equip_idis aserial, an auto-incrementing integer used as the primary key.typeandcolorare length-limited strings that must have a value.locationhas acheckconstraint allowing only one of eight preset values.install_dateis a date.
List the tables:
\dtOutput
List of relations
Schema | Name | Type | Owner
--------+------------+-------+-------
public | playground | table | sammy
(1 row)Describe the table's structure:
\d playgroundStep 7 — Adding, Querying, Updating and Deleting Data
Insert two rows:
INSERT INTO playground (type, color, location, install_date) VALUES ('slide', 'blue', 'south', '2024-04-28');
INSERT INTO playground (type, color, location, install_date) VALUES ('swing', 'yellow', 'northwest', '2024-08-16');Query the whole table:
SELECT * FROM playground;Output
equip_id | type | color | location | install_date
----------+-------+--------+-----------+--------------
1 | slide | blue | south | 2024-04-28
2 | swing | yellow | northwest | 2024-08-16
(2 rows)Change the swing's colour:
UPDATE playground SET color = 'red' WHERE type = 'swing';Delete the slide:
DELETE FROM playground WHERE type = 'slide';Add and drop a column:
ALTER TABLE playground ADD last_maint date;
ALTER TABLE playground DROP last_maint;Drop the table when you no longer need it:
DROP TABLE playground;Step 8 — Allowing Remote Connections (Optional)
By default PostgreSQL only listens on localhost. If your application runs on another machine, some extra configuration is needed.
Open the main configuration file (replace 14 with your version):
sudo nano /etc/postgresql/14/main/postgresql.confFind the listen_addresses line, remove the # and set it to:
listen_addresses = '*'Next, open the client authentication file:
sudo nano /etc/postgresql/14/main/pg_hba.confAdd the following line at the end to let the sammy role connect to the myapp database from your IP range using a password:
host myapp sammy 203.0.113.0/24 scram-sha-256Restart PostgreSQL and open port 5432 on the firewall, only for a specific IP address:
sudo systemctl restart postgresql
sudo ufw allow from 203.0.113.5 to any port 5432Warning: Never expose port 5432 to the whole internet. Restrict it by IP address or use an SSH tunnel or VPN.
Conclusion
You have installed PostgreSQL, learned how roles and peer authentication work, created a dedicated role and database for your application, and practised basic CRUD operations. Next, look into backups with pg_dump, performance tuning with indexes, or using PostgreSQL with ORMs such as Prisma and Drizzle.

