Getting a server. Install locally if you must, but a container is better for this course because you will be told to destroy it. docker run --name pg -e POSTGRES_PASSWORD=dev -p 5432:5432 -d postgres:16 is enough to begin. What matters more than the installation method is that you can recreate it from a written instruction, because every laboratory in this course is assessed partly on whether somebody else can reproduce your setup.
psql is the tool to learn, even if you also use pgAdmin or DBeaver. It is present on every server you will ever meet, it is scriptable, and its backslash commands are faster than any GUI for the things you do constantly: \l to list databases, \dt for tables, \d tablename for a table's full definition including its indexes and constraints, \du for roles, \timing to see how long each statement took, and \x to flip to expanded output when a row is too wide to read.
Roles, not users. PostgreSQL has one concept - the role - that serves as both user and group. A role with LOGIN is what other systems call a user; a role without it is what they call a group. Roles are cluster-wide rather than per-database, which surprises people migrating from MySQL. Privileges are granted to roles and roles are granted to other roles, which is how you build a permission structure that survives staff changes.
Schemas and search_path. A database contains schemas; a schema contains tables. The default schema is public. The search_path is an ordered list of schemas that unqualified names are resolved against, and it is responsible for a large share of the confusion in any multi-schema PostgreSQL installation: a table that exists is reported as not existing because it is in a schema that is not on the path. When something is missing and you are certain it is there, SHOW search_path; first.
Since PostgreSQL 15, public is no longer writable by every user by default, which is a security improvement and a migration surprise.
Types worth knowing before you design anything. PostgreSQL's type system is richer than the SQL standard requires, and using it well removes whole categories of application code.
text has no performance penalty against varchar(n) - use text with a CHECK constraint if you need a limit. timestamptz stores an instant and converts on the way in and out; timestamp stores wall-clock digits with no timezone and is almost always a mistake. Arrays let a column hold an ordered list of one type. JSONB stores parsed, indexable JSON and is the right home for genuinely schemaless attributes - but a JSONB column holding fields you query and constrain is a relational schema that has not been written down yet. Range types (int4range, tstzrange) model intervals, and with an exclusion constraint they enforce non-overlap - which is how you express "no two bookings for the same room may overlap" in the schema rather than in a service.
Laboratory exercise 1 - provision and verify a sandbox.
Provision a PostgreSQL instance you are free to destroy. Create a database, an application role and a schema, and set the role's search_path. Load at least 10,000 synthetic records with generate_series rather than typing them. Verify basic reads and writes, and record the server's version, data directory, shared_buffers and max_connections.
Deliverable: a single setup.sql plus a short README that a colleague can follow from nothing to a working sandbox without asking you a question, and the output of your verification queries. Reproducibility is the assessed property here, not elegance - if any step happened in a GUI and is not written down, the submission is incomplete.
-- ------------------------------------------------------------------
-- A sandbox, provisioned the way a laboratory submission should be:
-- every statement written down, nothing done by hand in a GUI.
-- ------------------------------------------------------------------
CREATE DATABASE workshop;
\c workshop
-- Roles. One for the application, one for read-only analysis.
-- NOLOGIN roles are groups; LOGIN roles are users.
CREATE ROLE app_rw LOGIN PASSWORD 'change_me';
CREATE ROLE analyst NOLOGIN;
CREATE ROLE reporting LOGIN PASSWORD 'change_me' IN ROLE analyst;
-- A schema of our own. Since PostgreSQL 15 the public schema is no
-- longer writable by all, and an application schema is better practice
-- in any case: it keeps your objects away from extensions.
CREATE SCHEMA ledger AUTHORIZATION app_rw;
-- search_path decides how unqualified names resolve. Set it per role
-- so the application does not have to qualify every table.
ALTER ROLE app_rw SET search_path = ledger, public;
SHOW search_path;
-- ------------------------------------------------------------------
-- The type system, used deliberately.
-- ------------------------------------------------------------------
CREATE TABLE ledger.account (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
-- text, not varchar(n). No performance difference; add a CHECK
-- when you actually need a limit.
holder text NOT NULL CHECK (length(holder) BETWEEN 1 AND 200),
-- timestamptz, never timestamp. This stores an instant; `timestamp`
-- stores wall-clock digits and loses the offset that made them mean
-- something.
opened_at timestamptz NOT NULL DEFAULT now(),
-- numeric for money. Never float: 0.1 + 0.2 <> 0.3 in binary, and
-- a ledger that does not balance is not a ledger.
balance_minor bigint NOT NULL DEFAULT 0,
currency char(3) NOT NULL CHECK (currency ~ '^[A-Z]{3}$'),
-- An array: an ordered list of one type, in one column.
tags text[] NOT NULL DEFAULT '{}',
-- JSONB for genuinely open attributes. If you find yourself
-- querying and constraining a key in here, it wants to be a column.
metadata jsonb NOT NULL DEFAULT '{}'::jsonb
);
-- A range type plus an exclusion constraint expresses "these may not
-- overlap" in the schema. The alternative is a SELECT-then-INSERT in
-- application code, which is a race condition with extra steps.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE ledger.rate_period (
currency char(3) NOT NULL,
validity tstzrange NOT NULL,
rate numeric(12,6) NOT NULL,
EXCLUDE USING gist (currency WITH =, validity WITH &&)
);
INSERT INTO ledger.rate_period VALUES
('GBP', tstzrange('2026-01-01', '2026-07-01'), 1.000000),
('GBP', tstzrange('2026-07-01', '2027-01-01'), 1.020000);
-- This one is rejected by the database, not by a service:
-- INSERT INTO ledger.rate_period VALUES
-- ('GBP', tstzrange('2026-06-01', '2026-08-01'), 1.5);
-- ERROR: conflicting key value violates exclusion constraint
-- ------------------------------------------------------------------
-- Verifying the install, which is the deliverable.
-- ------------------------------------------------------------------
SELECT version();
SELECT current_database(), current_user, current_schema();
SHOW data_directory; -- where the files are
SHOW shared_buffers; -- the memory settings you will tune later
SHOW max_connections;
-- Synthetic data, generated rather than typed. generate_series is the
-- function you will use in every laboratory in this course.
INSERT INTO ledger.account (holder, currency, balance_minor, tags)
SELECT
'Holder ' || n,
(ARRAY['GBP','USD','EUR'])[1 + (n % 3)],
(random() * 1000000)::bigint,
CASE WHEN n % 5 = 0 THEN ARRAY['vip'] ELSE ARRAY[]::text[] END
FROM generate_series(1, 10000) AS n;
SELECT count(*), currency FROM ledger.account GROUP BY currency;
Discussion
No questions on this topic yet. Sign in to ask the first one.