Relational databases and SQL
Mandla's Mountain Walks takes bookings by email and keeps them in a spreadsheet. That works for a handful a week. It stops working when two people in the office edit the sheet at once, when someone types "Lions Head" in one row and "Lion's Head" in the next, or when a group of nine is booked on a walk that takes eight. The Walk Office you build in this course keeps its information in a database instead: an organised store of data that a program manages for you, enforcing rules you set, for many users at once, without losing anything when the power fails.
This module teaches the most common kind, the relational database, and the language used to talk to it, SQL. You work in PostgreSQL through its command-line client, psql. By the end you create the Walk Office's first two tables, walks and users, load the six walks and four staff members, and answer real business questions with queries. Module 2 adds the bookings, departures and payments, and the joins that tie them together.
Why a relational database
You could keep Mandla's walks, bookings and payments in files, as the WEB-201 Walk Planner kept its walks in walks.json, but files leave all the hard problems to you. A database management system (DBMS) is a program that solves them once, for everyone:
- Rules that always hold
- You state once that a price must be more than zero, or that no two users share an email address, and the database refuses any change that breaks the rule, whichever program or person tries it.
- Many users at once
- Two office staff confirming bookings at the same moment do not overwrite each other's work.
- All or nothing
- A change made of several steps either happens completely or not at all, even if the server crashes halfway.
- Questions in one language
- "Which moderate walks cost under R700?" is one short query, not a loop you write by hand.
- Safe storage
- Once the database says a change is saved, it survives a power failure.
A relational database keeps all its data in tables, and links tables through the values they hold. It suits data with a clear structure, where the same kinds of facts are kept about many things, and where those things relate to each other: walks have departures, departures have bookings, bookings have payments. That describes most business software, which is why relational databases have been the default choice for decades.
They are not always the right tool. A few settings belong in a configuration file, and huge streams of log lines, or a cache that can be thrown away, often go in specialised stores. But for bookings and money, where a wrong or lost row costs a customer or a rand, a relational database is the safe choice.
PostgreSQL
This course uses PostgreSQL (often just "Postgres"), a free, open-source relational database developed in the open by a worldwide community since 1996, growing out of a University of California, Berkeley research project of the 1980s. It is strict about data and follows the SQL standard closely. The course teaches version 18, which you installed in Module 0. Almost everything here works the same in versions 15 to 18, and where version 18 differs, the lesson says so.
PostgreSQL is a server: a program that runs in the background, holds the data and waits for connections. Programs that connect to it are clients. In this module the client is psql, a terminal program. From Module 4, your PHP code is a client too, and later Laravel. One server holds several databases, each a separate collection of tables. Yours is mandlas_walks, owned by the login role walks_app that Module 0 created. A role is PostgreSQL's word for a user account.
The relational model in plain terms
The ideas behind relational databases come from mathematics, with words such as relation and tuple, but you need only the everyday versions:
- Table
- A named collection of facts about one kind of thing, such as
walks. The formal name is a relation. - Column
- One kind of fact that every row has, with a name and a data type, such as
price_zar, a whole number. - Row
- One thing: one walk, one user. Every row in a table has the same columns.
- Value
- What one row holds in one column, such as 650. Each value is a single item of the column's type, not a list.
- Primary key
- A column (or set of columns) whose value is different in every row, so each row can be found and referred to. In the Walk Office it is always a column called
id. - Foreign key
- A column that holds another table's primary key, to say which row there this row belongs to. A departure's
walk_idsays which walk it is. - Schema
- The design of the database: its tables, columns, types and rules. PostgreSQL also uses the word for a named folder of tables inside a database. Yours are in the default one,
public.
Three rules follow from the model. Rows have no built-in order, so whenever order matters you ask for it. Every value in a column has the column's type, so a price column never holds the word "TBC". And each fact is stored once: a booking refers to its walk by id instead of copying the walk's name. Module 2 turns that last rule into a method, called normalisation.
SQL
SQL (Structured Query Language, said "ess-queue-ell" or "sequel") is the language every relational database understands. It is declarative: you describe the result you want, and the database works out how to get it. A piece of SQL that does one thing is a statement, ending with a semicolon. Some statements define the structure (CREATE TABLE, ALTER TABLE, DROP TABLE), and others work with rows (INSERT, SELECT, UPDATE, DELETE). A SELECT is also called a query.
SQL keywords are not case-sensitive, but this course writes them in capitals and names in lower-case snake_case (price_zar, is_active), so you can tell them apart at a glance. Names that you write in lower case without quotes stay lower case. Avoid capitals and spaces in names, because they then need double quotes for ever after.
PostgreSQL and psql in practice
Open a terminal (on Windows, your WSL Ubuntu terminal) and connect to the Walk Office database:
$ psql -h localhost -U walks_app -d mandlas_walks
Password for user walks_app:
psql (16.15 (Ubuntu 16.15-0ubuntu0.24.04.1))
Type "help" for help.
mandlas_walks=>
-h localhost is the host, the computer the server runs on. -U is the role to connect as, and -d the database. Type the password you chose for walks_app in Module 0 (nothing appears as you type). The prompt mandlas_walks=> names the database, and ends in > for an ordinary role. A superuser sees # instead, which is a warning to be careful. The first line shows the version of psql and the server. This lesson was tested on version 16, so yours says 18 and a release number instead. Everything else looks the same.
At the prompt you can type SQL, which goes to the server, or meta-commands, which start with a backslash and are handled by psql itself. Meta-commands need no semicolon.
| Command | What it does |
|---|---|
\q | Quit psql (Ctrl+D also works) |
\? and \h CREATE TABLE | Help on meta-commands, and the syntax of any SQL statement |
\conninfo | Which database, role, host and port you are connected to |
\l and \dt | List the databases on the server, and the tables in this database |
\d walks and \d+ walks | Describe a table: columns, types, defaults, keys and constraints. The plus adds more detail |
\x | Turn expanded display on or off: one line per column, for wide rows |
\i sql/schema.sql | Run the SQL in a file, as if you had typed it |
\e | Open the last statement in an editor, to fix a long one |
\timing | Show how long each statement takes |
A statement can run over many lines. Until you type the semicolon, psql shows mandlas_walks->, with a hyphen, to say it is waiting for more. If you get lost in a half-typed statement, press Ctrl+C to abandon it. The up arrow brings back earlier lines.
Running SQL from files
Anything you want to keep, such as the design of your tables, belongs in a .sql file in your project, under Git, so you can run it again on a fresh database or on the server. There are two ways to run a file:
mandlas_walks=> \i sql/schema.sql
$ psql -h localhost -U walks_app -d mandlas_walks -f sql/schema.sql
\i runs it from inside psql, with paths relative to the folder you started psql in. psql -f runs it from the terminal and then exits, which suits scripts. By default psql carries on after an error, so a file whose third statement fails still runs the rest, leaving your database half changed and reporting success. Two options fix that:
$ psql -h localhost -U walks_app -d mandlas_walks -1 -v ON_ERROR_STOP=1 \
-f sql/schema.sql -f sql/seed.sql
-v ON_ERROR_STOP=1 stops at the first error and makes psql exit with a non-zero status (3), which scripts can test. -1 (single transaction) runs all the files as one transaction, so if anything fails, nothing at all is changed. The backslash at the end of the first line continues the command on the next line. Use this form for every file you run in this course.
Try it: find your way around
Connect to mandlas_walks and run \conninfo, \l and \dt. The last should say "Did not find any relations" until you create a table. Then run SELECT version(); and SELECT now();, and look at the time zone in the answer. Run \h INSERT and read the first few lines of the syntax. Quit with \q.
Transactions: autocommit until you say BEGIN
A transaction is a group of statements that succeed or fail as one. psql works in autocommit mode: each statement you type is its own transaction and is saved permanently the moment it succeeds. There is no undo. To group statements, and to give yourself an undo, start a transaction with BEGIN. Your changes are then visible only to you until you type COMMIT, which saves them for everyone, or ROLLBACK, which throws them away as if they had never happened.
mandlas_walks=> BEGIN;
BEGIN
mandlas_walks=*> UPDATE walks SET price_zar = 0 WHERE slug = 'pipe-track';
ERROR: new row for relation "walks" violates check constraint
"walks_price_zar_check"
mandlas_walks=!> SELECT 1;
ERROR: current transaction is aborted, commands ignored until end of
transaction block
mandlas_walks=!> ROLLBACK;
ROLLBACK
mandlas_walks=>
Watch the prompt. An asterisk (=*>) means you are inside a transaction, and an exclamation mark (=!>) means it has failed and only ROLLBACK will be accepted. Unlike many databases, PostgreSQL can also roll back CREATE TABLE, ALTER TABLE and DROP TABLE, which makes BEGIN a safe place to experiment with the structure as well as the data. (Some error lines in this lesson are shortened or wrapped to fit the page. Here your screen also shows a DETAIL line with the failing row.)
Data types that matter
Every column has a data type, which decides what values it accepts, how they sort and what you can do with them. The type is the first rule the database enforces for you.
| Type | Holds | Walk Office use |
|---|---|---|
integer | Whole numbers from about minus 2.1 billion to 2.1 billion | ascent_m, price_zar |
smallint | Whole numbers from -32,768 to 32,767 | max_group, group sizes |
bigint | Whole numbers up to about 9.2 million million million | Every id |
numeric(p,s) | Exact decimals with p digits in all, s after the point | distance_km numeric(4,1), coordinates |
real, double precision | Approximate (floating-point) numbers | Nothing: see below |
text | Text of any length | Names, slugs, summaries, emails |
varchar(n) | Text of at most n characters | Nothing, by choice: see below |
boolean | true, false (or NULL) | is_active |
date | A calendar day, no time | Qualification dates in Module 2 |
timestamptz | An exact moment in time | created_at, departure times |
Money: exact numbers, never floating point
The types real and double precision store numbers in binary floating point, which is fast but cannot hold most decimal fractions exactly, just as one third cannot be written exactly in decimals. That is fine for a temperature and wrong for money:
mandlas_walks=> SELECT 0.1::float8 + 0.2::float8 AS float_sum,
mandlas_walks-> 0.1::numeric + 0.2::numeric AS numeric_sum;
float_sum | numeric_sum
---------------------+-------------
0.30000000000000004 | 0.3
(1 row)
The :: is a cast: it converts a value to another type (float8 is a short name for double precision). The error looks tiny, but it grows over thousands of amounts, and a test such as = 0.3 quietly fails. Money therefore goes in one of two exact forms. The Walk Office stores whole rand in an integer, because Mandla never charges cents: price_zar integer holds 650 for R650. If you need cents, use numeric(10,2), which holds up to 99,999,999.99 exactly, or store whole cents in an integer. Avoid PostgreSQL's money type, whose output depends on the server's locale settings.
The column names say their units (price_zar, distance_km, ascent_m), so nobody has to guess. numeric(4,1) holds numbers up to 999.9 with one decimal place. A distance such as 123.45 is rounded to 123.5, and 1234.5 is refused with "numeric field overflow".
text or varchar
In PostgreSQL, text and varchar(n) are stored the same way, and the documentation states there is no performance difference between them. varchar(n) only adds a length limit, often a guess that later rejects a real customer's long name. This course uses text. You will meet varchar(255) in Laravel's tables in Module 7, which is fine too: the same type with a limit.
Dates, times and time zones
A date is a day on the calendar. For a moment in time, such as when a walk starts or when a booking was made, use timestamptz (timestamp with time zone). Despite its name it does not store a zone. It stores an exact instant, in UTC (Coordinated Universal Time) internally, and shows it in the session time zone, the zone your connection has chosen. The plain timestamp type stores a date and a clock time with no zone at all, so nobody can tell later which moment it meant. Avoid it.
mandlas_walks=> SET timezone = 'Africa/Johannesburg';
SET
mandlas_walks=> SELECT timestamptz '2026-12-05 05:00' AS walk_start;
walk_start
------------------------
2026-12-05 05:00:00+02
(1 row)
mandlas_walks=> SELECT timestamptz '2026-12-05 05:00'
mandlas_walks-> AT TIME ZONE 'Europe/London' AS london_clock;
london_clock
---------------------
2026-12-05 03:00:00
(1 row)
South Africa uses one zone, named Africa/Johannesburg in the time zone database, two hours ahead of UTC all year, with no daylight saving. The +02 in the output says so. A visitor in London sees the same Lion's Head sunrise start as 03:00 their time. Set the zone once for the whole database, so every connection uses it unless it asks otherwise. As the database owner, walks_app may do this:
ALTER DATABASE mandlas_walks SET timezone TO 'Africa/Johannesburg';
It takes effect on your next connection. Check with SHOW timezone;.
Identity columns, not serial
Each table needs a primary key, and the simplest is a number that the database hands out: 1, 2, 3 and so on. Modern PostgreSQL does this with an identity column:
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY
Older tutorials write id serial PRIMARY KEY. That still works, but serial is a PostgreSQL shortcut that creates a separate sequence object loosely tied to the column, which makes permissions, copying tables and changing the design awkward. Identity columns are part of the SQL standard, the sequence belongs to the column, and GENERATED ALWAYS adds a guard: PostgreSQL refuses any id you try to supply yourself, so a hand-typed id can never collide with one the database hands out later.
mandlas_walks=> INSERT INTO walks (id, slug, name) VALUES (99, 'test', 'Test');
ERROR: cannot insert a non-DEFAULT value into column "id"
DETAIL: Column "id" is an identity column defined as GENERATED ALWAYS.
HINT: Use OVERRIDING SYSTEM VALUE to override.
The ids are bigint because running out of ids in a busy table is a painful fix, and the extra four bytes cost almost nothing. Expect gaps: a failed insert, or one rolled back, still uses up its id. Ids identify rows. They are not a count.
Creating and changing tables
CREATE TABLE names the table and lists its columns, each with a name, a type and any rules. Here is the Walk Office's walks table, exactly as the project contract defines it:
CREATE TABLE walks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
slug text NOT NULL UNIQUE,
name text NOT NULL,
area text NOT NULL,
distance_km numeric(4,1) NOT NULL CHECK (distance_km > 0),
duration_hours numeric(3,1) NOT NULL CHECK (duration_hours > 0),
ascent_m integer NOT NULL CHECK (ascent_m >= 0),
difficulty text NOT NULL
CHECK (difficulty IN ('easy', 'moderate', 'hard')),
price_zar integer NOT NULL CHECK (price_zar > 0),
max_group smallint NOT NULL DEFAULT 8
CHECK (max_group BETWEEN 1 AND 8),
start_lat numeric(8,5) NOT NULL,
start_lon numeric(8,5) NOT NULL,
summary text NOT NULL,
is_active boolean NOT NULL DEFAULT true,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
The slug is a short, unique name for web addresses, as in /walks/lions-head. is_active lets Mandla retire a walk without deleting its history. created_at and updated_at record when the row was made and last changed, the "timestamps" Laravel adds to every table.
Constraints
A constraint is a rule the database enforces on every change, from every program. Forms and PHP code check data too, from Module 3, but a bug or a hand-typed command can slip past them. A constraint cannot be slipped past.
PRIMARY KEY- Unique and never empty. One per table.
NOT NULL- The column must have a value. Make this the norm, and leave a column nullable only when "not known" is a real answer, such as a phone number not yet given.
UNIQUE- No two rows may share a value in this column (or this set of columns), such as
slugor a user'semail. CHECK (condition)- Every row must make the condition true (or unknown, as you will see under NULL). Prices above zero, a difficulty from a fixed list, a group of 1 to 8.
DEFAULT value- Not strictly a rule: the value used when an insert leaves the column out. New walks start active, with a group limit of 8 and the current time.
REFERENCES other (id)- A foreign key, introduced below.
PostgreSQL names each constraint you do not name yourself: walks_pkey for the primary key, walks_slug_key for the unique slug, walks_price_zar_check for the price check, following the pattern table, column, kind. You can choose a name with CONSTRAINT name in front of the rule. Names matter because they appear in error messages, which is how you will know which rule a change broke. \d walks shows the whole design:
mandlas_walks=> \d walks
Table "public.walks"
Column | Type | Nullable | Default
----------------+--------------------------+----------+--------------
id | bigint | not null | generated
| | | always as
| | | identity
slug | text | not null |
name | text | not null |
...
price_zar | integer | not null |
max_group | smallint | not null | 8
...
is_active | boolean | not null | true
created_at | timestamp with time zone | not null | now()
updated_at | timestamp with time zone | not null | now()
Indexes:
"walks_pkey" PRIMARY KEY, btree (id)
"walks_slug_key" UNIQUE CONSTRAINT, btree (slug)
Check constraints:
"walks_ascent_m_check" CHECK (ascent_m >= 0)
"walks_difficulty_check" CHECK (difficulty = ANY (ARRAY['easy'::text,
'moderate'::text, 'hard'::text]))
"walks_distance_km_check" CHECK (distance_km > 0::numeric)
"walks_duration_hours_check" CHECK (duration_hours > 0::numeric)
"walks_max_group_check" CHECK (max_group >= 1 AND max_group <= 8)
"walks_price_zar_check" CHECK (price_zar > 0)
PostgreSQL rewrites some checks in its own form (IN becomes = ANY (ARRAY[...])), with the same meaning. The primary key and the unique slug are each backed by an index, a lookup structure that makes finding a value fast, taught in Module 2.
ALTER TABLE and DROP TABLE
Designs change. ALTER TABLE changes a table that already holds data:
ALTER TABLE walks ADD COLUMN meeting_point text;
ALTER TABLE walks ADD COLUMN min_age smallint NOT NULL DEFAULT 12;
ALTER TABLE walks ADD CONSTRAINT walks_min_age_check
CHECK (min_age BETWEEN 0 AND 18);
ALTER TABLE walks ALTER COLUMN meeting_point SET NOT NULL;
ALTER TABLE walks RENAME COLUMN meeting_point TO meeting_place;
ALTER TABLE walks DROP COLUMN meeting_place;
The database protects existing rows. Adding min_age with NOT NULL works only because the DEFAULT fills it in for all six walks. Setting meeting_point to NOT NULL fails with "column "meeting_point" of relation "walks" contains null values" until every row has one. Adding a check that some row already breaks, such as a price cap of R800, fails with "check constraint "walks_price_cap" of relation "walks" is violated by some row". Fix the data first, then add the rule.
DROP TABLE walks; deletes the table, its rows and its constraints at once, with no confirmation and no recycle bin. DROP TABLE IF EXISTS walks; does the same without an error when the table is not there, which is useful at the top of a script you want to run many times. If another table refers to it through a foreign key, PostgreSQL refuses ("cannot drop table walks because other objects depend on it") and hints at DROP ... CASCADE. Read that hint as a warning, not an instruction.
Foreign keys: a first look
A foreign key links a row to a row in another table, and the database guarantees the link is real. Module 2 creates the Walk Office's departures table, where each departure belongs to one walk. Here is a cut-down version, tried inside a transaction so nothing stays behind:
mandlas_walks=> BEGIN;
BEGIN
mandlas_walks=*> CREATE TABLE departures_demo (
mandlas_walks(*> id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
mandlas_walks(*> walk_id bigint NOT NULL REFERENCES walks (id)
mandlas_walks(*> ON DELETE RESTRICT,
mandlas_walks(*> starts_at timestamptz NOT NULL
mandlas_walks(*> );
CREATE TABLE
mandlas_walks=*> INSERT INTO departures_demo (walk_id, starts_at)
mandlas_walks-*> VALUES (42, '2026-12-05 08:00');
ERROR: insert or update on table "departures_demo" violates foreign key
constraint "departures_demo_walk_id_fkey"
DETAIL: Key (walk_id)=(42) is not present in table "walks".
mandlas_walks=!> ROLLBACK;
ROLLBACK
There is no walk 42, so the departure is refused. The other direction matters as much: what should happen to departures when someone deletes their walk? The ON DELETE part of the foreign key decides.
With ON DELETE RESTRICT, deleting the Pipe Track while departures refer to it fails: "update or delete on table "walks" violates foreign key constraint ... Key (id)=(3) is still referenced from table "departures_demo"". With ON DELETE CASCADE, the delete succeeds and quietly takes both departures with it. For business records such as departures, bookings and payments, RESTRICT is almost always right: history should be retired on purpose, not wiped by accident. CASCADE suits rows that mean nothing without their parent, such as the link between a guide and a walk they may lead. Module 2 designs every foreign key in the Walk Office with these choices.
In the prompt above, (*> means psql is inside a bracket and a transaction, still waiting for the statement to end.
Adding rows: INSERT
INSERT adds rows. Name the columns you are filling, then give the values in the same order. Columns you leave out get their default (an identity value, now(), true, 8) or NULL. One statement can insert many rows, separated by commas:
INSERT INTO walks
(slug, name, area, distance_km, duration_hours, ascent_m,
difficulty, price_zar, start_lat, start_lon, summary)
VALUES
('lions-head', 'Lion''s Head sunrise',
'Table Mountain National Park', 5.5, 3, 370, 'moderate', 650,
-33.936, 18.389,
'A steady climb with chains near the top, to watch the sun rise '
'over the city.'),
('platteklip', 'Platteklip Gorge to the top of Table Mountain',
'Table Mountain National Park', 6, 4, 750, 'hard', 850,
-33.949, 18.403,
'The classic route up the front of Table Mountain, steep and rocky, '
'with the cable car as an option down.')
RETURNING id, slug, price_zar;
Text values go in single quotes. Double quotes are for names, not text, so "easy" would mean a column called easy. A single quote inside text is written twice: 'Lion''s Head sunrise' stores Lion's Head sunrise. Numbers have no quotes. Two quoted pieces of text separated only by a line break are joined into one, which keeps long summaries inside 80 characters per line. Always list the columns: INSERT INTO walks VALUES (...) without a list depends on the column order, and breaks silently when a column is added.
RETURNING makes the insert answer like a query, with the rows it created. It is the way to learn the ids PostgreSQL handed out, which your PHP code needs in Module 4 to show a new booking's details:
id | slug | price_zar
----+----------------+-----------
1 | lions-head | 650
2 | platteklip | 850
3 | pipe-track | 450
4 | skeleton-gorge | 900
5 | silvermine | 600
6 | cape-point | 550
(6 rows)
INSERT 0 6
The last line is the command tag: INSERT 0 6 means six rows inserted (the 0 is a leftover from old versions). Every statement reports one, such as UPDATE 1 or DELETE 0. Read it every time: it tells you how many rows your statement touched.
Asking questions: SELECT
A query has up to six parts, always written in this order. Only SELECT is required.
SELECT columns or expressions -- what to show
FROM table -- where from
WHERE condition -- which rows
ORDER BY columns -- in what order
LIMIT n -- how many
OFFSET m; -- after skipping how many
Anything after two hyphens is a comment, ignored by PostgreSQL. SELECT * means every column, which is handy at the prompt, but in saved files and in application code name the columns you need: the result is clearer, and it does not change when someone adds a column. An expression in the SELECT list can be given a column heading with AS, called an alias.
PostgreSQL does not work through the clauses in the order you write them. It takes the rows FROM the table, keeps those that pass WHERE, works out the SELECT list, sorts with ORDER BY, and finally applies OFFSET and LIMIT. That explains a rule that puzzles many people: you can sort by an alias, because ORDER BY comes after SELECT, but you cannot filter by one in WHERE, which comes before.
WHERE: choosing rows
WHERE holds a condition, and only rows that make it true appear in the result.
| Operator | Meaning | Example |
|---|---|---|
= and <> (or !=) | Equal, not equal | difficulty = 'hard' |
<, <=, >, >= | Less than, at most, more than, at least | duration_hours < 3 |
AND, OR, NOT | Both, either, the opposite | is_active AND price_zar < 700 |
IN (list) | Equal to any item in the list | difficulty IN ('easy', 'moderate') |
BETWEEN a AND b | From a to b, both included | price_zar BETWEEN 500 AND 700 |
LIKE, ILIKE | Matches a pattern, with or without caring about capitals | name ILIKE '%gorge%' |
IS NULL, IS NOT NULL | Has no value, has a value | phone IS NULL |
Text comparisons are exact and case-sensitive: difficulty = 'Hard' finds nothing. In a pattern, % stands for any run of characters, including none, and _ for exactly one character. So LIKE '%Table Mountain%' finds the text anywhere, and LIKE 'S%' finds values starting with a capital S. ILIKE, a PostgreSQL addition, ignores the difference between capitals and small letters, which suits a visitor's search box.
AND binds more tightly than OR, as multiplication does before addition. difficulty = 'easy' OR difficulty = 'moderate' AND price_zar < 600 means "easy walks of any price, or moderate walks under R600", which is probably not what was meant. Use brackets whenever you mix them, or use IN.
mandlas_walks=> SELECT name, difficulty, duration_hours
mandlas_walks-> FROM walks
mandlas_walks-> WHERE difficulty IN ('easy', 'moderate')
mandlas_walks-> AND duration_hours <= 3
mandlas_walks-> ORDER BY duration_hours;
name | difficulty | duration_hours
--------------------------------------+------------+----------------
Cape Point lighthouse and Diaz Beach | easy | 2.0
The Pipe Track | easy | 2.5
Lion's Head sunrise | moderate | 3.0
(3 rows)
ORDER BY, LIMIT, OFFSET and DISTINCT
ORDER BY price_zar sorts from smallest to largest (ASC, the default), and ORDER BY price_zar DESC from largest. List more columns to break ties: ORDER BY difficulty, price_zar DESC, name. Text sorts alphabetically, dates from earliest. Without ORDER BY, the order is whatever PostgreSQL finds quickest, and it can change between runs.
LIMIT 3 keeps the first three rows, and OFFSET 2 skips two first. Together they give pages: LIMIT 20 OFFSET 40 is page 3 of a list shown 20 at a time. Only ever use them with ORDER BY, or "the first three" means any three. For very deep pages OFFSET gets slow, because the skipped rows are still worked out, but for the office's bookings list it is fine, and Laravel's paginator in Module 8 uses it.
SELECT DISTINCT area FROM walks removes duplicate rows from the result, giving each area once. It applies to the whole row of the result, not to one column.
Try it: ask the walks table questions
Once your tables and seed data exist (the practical builds them), write queries for: the hard walks, most expensive first. Walks whose name contains "head" in any capitals. Walks from 4 to 6 km long. The two shortest walks by duration. Each distinct difficulty. Before you run each, predict how many rows you will get, then check the row count at the bottom.
NULL and three-valued logic
NULL is SQL's marker for a missing or unknown value. It is not zero, not an empty string and not false: it means "no value here". Aisha Patel has not given the office a phone number, so her phone is NULL. Because NULL means unknown, any comparison with it gives an unknown answer, which SQL also writes as NULL. Is an unknown phone number equal to '021 555 0142'? Unknown. Is NULL equal to NULL? Also unknown, because two unknown numbers may or may not be the same.
So SQL conditions have three possible results, true, false and unknown, which is called three-valued logic. WHERE keeps only rows where the condition is true, so unknown rows disappear quietly:
mandlas_walks=> SELECT name, phone FROM users WHERE phone = NULL;
name | phone
------+-------
(0 rows)
mandlas_walks=> SELECT name, phone FROM users WHERE phone IS NULL;
name | phone
-------------+-------
Aisha Patel |
(1 row)
mandlas_walks=> SELECT name, phone FROM users WHERE phone <> '021 555 0142';
name | phone
--------------+--------------
Mandla Dube | 082 555 0101
Sipho Ndlovu | 083 555 0177
(2 rows)
The first query can never find anything, because = NULL is never true. Always test with IS NULL or IS NOT NULL. The third query looks as if it should list everyone except Zanele, but Aisha is missing too: for her, the comparison is unknown. When you want such rows, say so: WHERE phone <> '021 555 0142' OR phone IS NULL.
| Expression | Result | Why |
|---|---|---|
true AND NULL | NULL (unknown) | Depends on the unknown part |
false AND NULL | false | False whatever the unknown is |
true OR NULL | true | True whatever the unknown is |
false OR NULL | NULL (unknown) | Depends on the unknown part |
NOT NULL | NULL (unknown) | The opposite of unknown is unknown |
NULLs also affect sorting (in PostgreSQL they come last in ascending order, first in descending, unless you add NULLS FIRST or NULLS LAST) and constraints. A CHECK passes when its condition is unknown, so CHECK (price_zar > 0) alone would let a NULL price through. That is why the Walk Office pairs checks with NOT NULL. A UNIQUE column allows many NULLs, because no two unknowns count as equal.
COALESCE(a, b, ...) returns the first of its arguments that is not NULL, which is how you show a placeholder: COALESCE(phone, '-') shows a hyphen where there is no phone number. Use it for display. Do not use it to hide NULLs that should not be there: that is the job of NOT NULL.
Expressions and functions
A query can calculate as well as fetch. Arithmetic uses + - * /, and functions are called with brackets. Give each calculated column an alias, or its heading is just ?column?.
SELECT name,
price_zar,
round(price_zar * 0.9) AS group_price_zar,
round(price_zar * 0.9) * 4 AS total_for_4_zar
FROM walks
ORDER BY price_zar;
Mandla's rule is 10% off per person for groups of 4 or more, rounded to the nearest rand, so the Lion's Head costs R585 per person and R2,340 for four. round() on an exact numeric rounds halves away from zero, so R612.50 becomes R613. Watch whole-number division: when both sides are integers, / throws away the fraction, so 7 / 2 is 3. Make one side numeric to keep it: 7 / 2.0, or ascent_m / price_zar::numeric.
| Expression | Result |
|---|---|
lower('Mandla@MandlasWalks.co.za') | mandla@mandlaswalks.co.za |
upper('pipe-track') | PIPE-TRACK |
length('Lion''s Head') | 11 |
name || ' (' || role || ')' | Sipho Ndlovu (guide) |
concat('Phone: ', phone) | Phone: when phone is NULL |
|| joins text. If any part is NULL, the whole result is NULL, so 'Phone: ' || phone is NULL for Aisha. concat() treats NULLs as empty text instead. Choose on purpose. The Walk Office stores emails in lower case, and the users table enforces it with CHECK (email = lower(email)), so "Zanele@..." and "zanele@..." can never become two accounts.
| Expression | Gives |
|---|---|
now() | The current moment as a timestamptz (the start of the current transaction) |
current_date | Today's date in the session time zone |
date_trunc('month', timestamptz '2026-12-05 05:00') | 2026-12-01 00:00:00+02, the start of that month |
extract(year FROM date '2026-12-05') | 2026. Also month, day, hour, and isodow (1 Monday to 7 Sunday) |
age(date '2026-12-05', date '1990-03-21') | 36 years 8 mons 15 days |
date '2026-12-05' - current_date | Whole days from today to 5 December 2026 |
date_trunc is how you group by month or day in reports (Module 2). extract(isodow ...) tells you whether a date falls on a weekend. Because now() stays the same for the whole of a transaction, every row changed in one transaction gets the same updated_at, which is usually what you want.
Try it: calculate
Write one query that lists each walk's name, its price per kilometre rounded to two decimals, and its slug in capitals, ordered by price per kilometre. Then find the day of the week of 24 December 2026 with extract(isodow ...), and how many days away it is.
Changing and removing rows: UPDATE and DELETE
UPDATE changes values in existing rows, and DELETE removes rows. Both use WHERE to choose which rows, exactly as SELECT does, and both accept RETURNING.
UPDATE walks
SET price_zar = 690,
updated_at = now()
WHERE slug = 'lions-head'
RETURNING slug, price_zar;
Set updated_at yourself, because its default applies only when a row is created (Laravel does it for you from Module 7). Choose rows by something stable and unique, such as the slug or the id.
Leave out the WHERE, and the statement applies to every row in the table. UPDATE walks SET price_zar = 500; makes all six walks cost R500, and DELETE FROM users; removes all four staff. In autocommit mode that happens instantly and for good. This is the most common serious mistake in SQL, and experienced people make it too.
mandlas_walks=> BEGIN;
BEGIN
mandlas_walks=*> UPDATE walks SET price_zar = 500;
UPDATE 6
mandlas_walks=*> ROLLBACK;
ROLLBACK
The command tag UPDATE 6 gave the game away: one price change should touch one row. Build a habit that makes the mistake harmless:
- Write the
WHEREclause first, in aSELECT:SELECT slug, price_zar FROM walks WHERE slug = 'lions-head';. Check it finds exactly the rows you mean. - Type
BEGIN;. - Turn the
SELECTinto theUPDATEorDELETE, keeping the sameWHERE, withRETURNINGto see the result. - Read the command tag. If the count is what you expected,
COMMIT;. If not,ROLLBACK;and think again.
Worked example: the Skeleton Gorge ladders are closed for repairs
Imagine the ladders in Skeleton Gorge close for a month of repairs, and Mandla asks Zanele to take the walk off the website and lower the Platteklip price by R50 for the same month to fill the gap. She works through the habit.
mandlas_walks=> SELECT slug, is_active, price_zar FROM walks
mandlas_walks-> WHERE slug IN ('skeleton-gorge', 'platteklip');
slug | is_active | price_zar
----------------+-----------+-----------
platteklip | t | 850
skeleton-gorge | t | 900
(2 rows)
mandlas_walks=> BEGIN;
BEGIN
mandlas_walks=*> UPDATE walks SET is_active = false, updated_at = now()
mandlas_walks-*> WHERE slug = 'skeleton-gorge'
mandlas_walks-*> RETURNING slug, is_active;
slug | is_active
----------------+-----------
skeleton-gorge | f
(1 row)
UPDATE 1
mandlas_walks=*> UPDATE walks SET price_zar = price_zar - 50, updated_at = now()
mandlas_walks-*> WHERE slug = 'platteklip'
mandlas_walks-*> RETURNING slug, price_zar;
slug | price_zar
------------+-----------
platteklip | 800
(1 row)
UPDATE 1
mandlas_walks=*> COMMIT;
COMMIT
Each change touched one row, as intended, so she commits both together. Had the second failed, the transaction would have aborted and the first would not have happened either: the two succeed or fail together. price_zar - 50 calculates from the value in the row, so she needed no lookup. A month later she reverses both the same way. Nothing was deleted, so nothing needs rebuilding.
Reading PostgreSQL's error messages
PostgreSQL's error messages are precise, and reading them carefully saves more time than any other habit. A message has up to four parts. ERROR says what went wrong. DETAIL gives the specific values. HINT, when present, suggests a fix. For syntax and name errors, LINE shows your statement with a caret (^) under the place where PostgreSQL gave up.
mandlas_walks=> SELEC * FROM walks;
ERROR: syntax error at or near "SELEC"
LINE 1: SELEC * FROM walks;
^
mandlas_walks=> SELECT nme FROM walks;
ERROR: column "nme" does not exist
LINE 1: SELECT nme FROM walks;
^
HINT: Perhaps you meant to reference the column "walks.name".
mandlas_walks=> SELECT * FROM walk;
ERROR: relation "walk" does not exist
LINE 1: SELECT * FROM walk;
^
A relation is PostgreSQL's word for a table (or anything table-like). "Syntax error at or near" points to where the parser got confused, and the real mistake is often just before that point, such as a missing comma on the line above.
Constraint violations name the constraint, which is why names matter. Each also carries a five-character SQLSTATE code, which programs use to tell errors apart. In Module 4 your PHP code will catch code 23505 to tell a visitor "that email address is already registered". Type \errverbose straight after an error to see the code and more:
mandlas_walks=> INSERT INTO users (name, email, password, role)
mandlas_walks-> VALUES ('Thabo Mokoena', 'zanele@mandlaswalks.co.za',
mandlas_walks(> 'not-set', 'office');
ERROR: duplicate key value violates unique constraint "users_email_key"
DETAIL: Key (email)=(zanele@mandlaswalks.co.za) already exists.
mandlas_walks=> \errverbose
ERROR: 23505: duplicate key value violates unique constraint "users_email_key"
DETAIL: Key (email)=(zanele@mandlaswalks.co.za) already exists.
SCHEMA NAME: public
TABLE NAME: users
CONSTRAINT NAME: users_email_key
LOCATION: _bt_check_unique, nbtinsert.c:666
| Message starts | SQLSTATE | Meaning and usual fix |
|---|---|---|
| null value in column "name" of relation "walks" violates not-null constraint | 23502 | A required column was left out or given NULL. Supply it, or check the column list matches the values. |
| duplicate key value violates unique constraint "walks_slug_key" | 23505 | That value is already used. The DETAIL line names it. Choose another, or update the existing row. |
| new row for relation "walks" violates check constraint "walks_difficulty_check" | 23514 | A value broke a rule. The DETAIL line shows the whole failing row: look for Easy with a capital, a zero price, a group of 9. |
| insert or update on table ... violates foreign key constraint | 23503 | The row refers to something that does not exist. Insert the parent first, or fix the id. |
| update or delete on table "walks" violates foreign key constraint | 23503 | Other rows still refer to this one. Deal with them first, or retire the row instead. |
| invalid input syntax for type integer: "abc" | 22P02 | Text that cannot become the column's type. Check quotes and values. |
Try it: break every rule once
Inside BEGIN, try to insert a walk with each mistake in turn: a slug that already exists, the difficulty 'Easy', a price of 0, no name, a hand-typed id, and a distance of 1234.5. Read each message and name the constraint or rule that caught it, then ROLLBACK. The practical has you record these in your notes.
The Walk Office database, first milestone
In the practical work you create the project's SQL files in ~/projects/walks-sql, the folder the project contract fixes for Modules 1 and 2:
walks-sql/
sql/
schema.sql CREATE TABLE walks and users (Module 2 adds the rest)
seed.sql the six walks and the four staff users
queries.sql business questions answered in SQL
README.md what the project is and how to rebuild the database
schema.sql starts with DROP TABLE IF EXISTS, so it gives a clean, empty design every time, and seed.sql fills it. Together they rebuild the database in one command, so you can experiment freely. queries.sql is a library of answered questions that changes nothing.
The users table holds Mandla's staff, not customers, who get their own table in Module 2. Its role decides what each person may do: admin for Mandla, office for Zanele Khumalo, and guide for Sipho Ndlovu and Aisha Patel. Its password column holds a placeholder, not-set, for now. Real passwords are never stored as typed: Module 8 stores a one-way hash, a scrambled value that can check a password but cannot be turned back into it. Until then nobody can log in, which is exactly right.
Sources
- PostgreSQL 18 documentation, "psql": https://www.postgresql.org/docs/18/app-psql.html
- PostgreSQL 18 documentation, "Numeric Types": https://www.postgresql.org/docs/18/datatype-numeric.html
- PostgreSQL 18 documentation, "Character Types": https://www.postgresql.org/docs/18/datatype-character.html
- PostgreSQL 18 documentation, "Date/Time Types": https://www.postgresql.org/docs/18/datatype-datetime.html
- PostgreSQL 18 documentation, "Identity Columns": https://www.postgresql.org/docs/18/ddl-identity-columns.html
- PostgreSQL 18 documentation, "Constraints": https://www.postgresql.org/docs/18/ddl-constraints.html
- PostgreSQL 18 documentation, "CREATE TABLE": https://www.postgresql.org/docs/18/sql-createtable.html
- PostgreSQL 18 documentation, "ALTER TABLE": https://www.postgresql.org/docs/18/sql-altertable.html
- PostgreSQL 18 documentation, "INSERT": https://www.postgresql.org/docs/18/sql-insert.html
- PostgreSQL 18 documentation, "SELECT": https://www.postgresql.org/docs/18/sql-select.html
- PostgreSQL 18 documentation, "UPDATE": https://www.postgresql.org/docs/18/sql-update.html
- PostgreSQL 18 documentation, "DELETE": https://www.postgresql.org/docs/18/sql-delete.html
- PostgreSQL 18 documentation, "Transactions" (tutorial): https://www.postgresql.org/docs/18/tutorial-transactions.html
- PostgreSQL 18 documentation, "Comparison Functions and Operators": https://www.postgresql.org/docs/18/functions-comparison.html
- PostgreSQL 18 documentation, "Pattern Matching": https://www.postgresql.org/docs/18/functions-matching.html
- PostgreSQL 18 documentation, "Conditional Expressions" (COALESCE): https://www.postgresql.org/docs/18/functions-conditional.html
- PostgreSQL 18 documentation, "String Functions and Operators": https://www.postgresql.org/docs/18/functions-string.html
- PostgreSQL 18 documentation, "Date/Time Functions and Operators": https://www.postgresql.org/docs/18/functions-datetime.html
- PostgreSQL 18 documentation, "PostgreSQL Error Codes": https://www.postgresql.org/docs/18/errcodes-appendix.html
- PostgreSQL 18 documentation, "Release 18": https://www.postgresql.org/docs/18/release-18.html
- PostgreSQL wiki, "Don't Do This": https://wiki.postgresql.org/wiki/Don%27t_Do_This