PostgreSQL Cheat Sheet

In progress

Connecting to PostgreSQL, creating databases and roles, and running a local server with Docker Compose.

Overview

Task Command
Connect as the postgres superuser on a Linux server sudo -u postgres psql
Connect locally (Homebrew install) psql -d postgres
Connect as a given role psql -d postgres -U appuser
Connection URL for Django or Flask postgres://USER:PASSWORD@HOST:PORT/NAME

Details

Databases and Roles

CREATE ROLE appuser WITH LOGIN PASSWORD '...';
CREATE DATABASE appdb OWNER appuser;          -- owner can create tables in public
ALTER ROLE appuser CREATEDB;                   -- only if the app must create databases (test runners)
\l                                             -- list databases
\c appdb                                       -- connect to another database
\du                                            -- list roles
SELECT now();                                  -- quick connectivity check

Local Server with Docker Compose

services:
  db:
    image: postgres:16.4                     # a pinned version, not :latest
    env_file: .env                           # POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB
    ports:
      - "127.0.0.1:5432:5432"                # reachable from this machine only
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:
docker compose up -d
docker compose exec db psql -U appuser -d appdb

If psql complains that role root doesn't exist, pass the user explicitly with -U: without it, psql uses your shell user name.

References