OpenBSD PostgreSQL Database - Beginner Guide

OpenBSD PostgreSQL Database - Beginner Guide

PostgreSQL is a powerful open-source database. Here's how to install and use it on OpenBSD.

Step 1: Install PostgreSQL

OpenBSD makes it easy with pkg_add:
pkg_add postgresql15-server - installs PostgreSQL 15

Important:
This installs the server only. You may also want:
pkg_add postgresql15-contrib - additional tools and extensions

Step 2: Initialize the Database

PostgreSQL needs to be initialized before first use:
pkg_add postgresql15-server (if not already done)
postgresql-setup init - initializes the database cluster

This creates the data directory at:
/var/postgres

Step 3: Start PostgreSQL

Start the database server:
rcctl enable postgresql-15 - enables on boot
rcctl start postgresql-15 - starts immediately

Check status: rcctl status postgresql-15

The first time you start it, it may print some informational messages - this is normal.

Step 4: Connect to PostgreSQL

Switch to the postgres system user:
su - postgres
Enter your password (the one you set during installation)

Now connect to the database:
psql
You should see a prompt: =#

Common first commands:
\\l - list all databases
\\du - list all users/roles
\\q - quit PostgreSQL

Step 5: Create Your First Database

While logged in as the postgres user:
createdb myfirstdb - creates a new database named "myfirstdb"

To quit PostgreSQL: \\q, then type exit to exit the su session.

To connect later: You can use:
psql myfirstdb (as any user with permission)
psql -U youruser -d myfirstdb (with username specified)

Step 5: Basic SQL Commands

Inside the PostgreSQL prompt (=#):
CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT, email TEXT);
INSERT INTO users (name, email) VALUES ('John', 'john@example.com');
SELECT * FROM users; - view your data
\\q - quit

Full tutorials: Search for "PostgreSQL tutorial" for more comprehensive learning.

Ready for more OpenBSD topics? Use the lesson navigation to continue.

Article author: Arthur Isaev