5 tasks, about 7.5 hours
This week the Walk Office gets its first real data: the walks and users tables in the mandlas_walks database, the six walks and four staff members, and a file of business questions answered in SQL. Work in ~/projects/walks-sql, connected as walks_app, and keep your findings in docs/module-1-notes.md. On Windows, do everything in your WSL Ubuntu terminal. You need PostgreSQL, psql, VS Code and Git from Module 0. Together the five tasks take about seven and a half hours.
Task 1: Set up the project and find your way around psql
- Create the project folder with
mkdir -p ~/projects/walks-sql/sql ~/projects/walks-sql/docs(Module 0 may have made it already). Inside it, rungit initif it is not a repository yet, thengit switch -c module-1so this week's work goes on its own branch. Open the folder in VS Code. - Connect with
psql -h localhost -U walks_app -d mandlas_walks. Run\conninfo,\land\dt, and record in your notes which database, role and port you are using. If typing the password every time annoys you, set up~/.pgpassas the lesson shows, withchmod 600. - Set the database's time zone with
ALTER DATABASE mandlas_walks SET timezone TO 'Africa/Johannesburg';, quit, connect again, and checkSHOW timezone;andSELECT now();. Record what the+02means. - Run these experiments at the prompt and record each result with one sentence explaining it:
SELECT 0.1::float8 + 0.2::float8, 0.1::numeric + 0.2::numeric;,SELECT 7 / 2, 7 / 2.0;,SELECT round(612.5), round(650 * 0.9);, andSELECT 1234.5::numeric(4,1);. - Show one moment in two zones:
SELECT timestamptz '2026-12-05 05:00';, then the same withAT TIME ZONE 'Europe/London'. Then trySELECT NULL = NULL, NULL IS NULL, true OR NULL, false AND NULL;and explain the four answers in your notes. - Run
\h CREATE TABLEand\?, and add to your notes the five meta-commands you expect to use most, with what each does.
What you produce: the walks-sql repository on a module-1 branch, the database set to South African time, and docs/module-1-notes.md with your connection details (never the password), the experiment results and explanations, and your meta-command list.
Time: 1 hour 15 minutes.
Task 2: Write sql/schema.sql and test every constraint
- Create
sql/schema.sql. Start it with a comment saying what it is and how to run it, thenDROP TABLE IF EXISTS users;andDROP TABLE IF EXISTS walks;so it can be run again and again. - Add the
walkstable exactly as the lesson shows it, typing it rather than pasting, so you think about each type and rule as you go. - Design the
userstable yourself from this description: an identity primary keyid. A requiredname. A required, uniqueemailthat must be stored in lower case. A requiredpasswordcolumn of type text, which holds a placeholder until Module 8 (add a comment saying so). A requiredrolethat may only beadmin,officeorguide. An optionalphone. Andcreated_atandupdated_atas inwalks. - Run the file with
psql -h localhost -U walks_app -d mandlas_walks -1 -v ON_ERROR_STOP=1 -f sql/schema.sql. Fix any error, then run it a second time to prove it can be repeated. Check both tables with\d walksand\d users, and compare every column with the project contract's tables. - Test the rules. In psql, type
BEGIN;, then try to insert rows that break each rule in turn: a walk with difficulty'Easy', a price of 0, no name, a hand-typed id, a distance of 1234.5, and amax_groupof 9. Then a user with role'manager'and a user whose email has a capital letter. After each error, typeROLLBACK;andBEGIN;again (the failed transaction accepts nothing else). Record each error's first line and the constraint it names. - Try a foreign key, also inside a transaction: create the
departures_demotable from the lesson withON DELETE RESTRICT, insert a departure for a walk that does not exist, and record the error. (You need a walk to test deleting: come back to this step after Task 3, insert two departures for the Pipe Track, try to delete the walk, then repeat withON DELETE CASCADEand see what is left indepartures_demo. End withROLLBACK;both times.)
What you produce: sql/schema.sql creating walks and users exactly as the contract describes, runnable any number of times, and a table in your notes of eight broken rules with the error and constraint name each gave, plus what RESTRICT and CASCADE did.
How to check: \d users shows a primary key users_pkey, a unique constraint users_email_key and two check constraints, and \dt lists exactly two tables owned by walks_app.
Time: 2 hours.
Task 3: Write sql/seed.sql with the walks and the staff
- Create
sql/seed.sqlwith oneINSERTfor all six walks, copying every value from the table of walks in the project contract (slug, name, area, distance, duration, ascent, difficulty, price and start point). For each summary, write one sentence describing the walk, or use the summaries from the WEB-201 Walk Planner if you have them. Remember to double the apostrophe in "Lion's Head" and "Elephant's Eye". End the statement withRETURNING id, slug, price_zar. - Add a second
INSERTfor the four staff users: Mandla Dube (admin), Zanele Khumalo (office), Sipho Ndlovu and Aisha Patel (bothguide). Give each an email atmandlaswalks.co.zain lower case, the placeholder password'not-set', and an invented phone number in the 555 range, except Aisha, whose phone is NULL because she has not given one yet. End withRETURNING id, name, role. - Rebuild the database in one command:
psql -h localhost -U walks_app -d mandlas_walks -1 -v ON_ERROR_STOP=1 -f sql/schema.sql -f sql/seed.sql. Read theRETURNINGoutput and the command tagsINSERT 0 6andINSERT 0 4. - Check the data against the contract with a query that lists every walk's slug, distance, duration, ascent, difficulty, price and start point, ordered by id. Turn on
\xand look at one whole walk. Check that the defaults filledmax_group,is_activeand the timestamps. - Run the seed file a second time on its own, without the schema file, and record what happens and why. Then rebuild with both files again.
What you produce: sql/seed.sql, which with schema.sql rebuilds the Walk Office's first data in one command: six walks matching the contract value for value, and four staff users.
Time: 1 hour 15 minutes.
Task 4: Answer Mandla's questions in sql/queries.sql
- Create
sql/queries.sql. For each question below, write a numbered comment with the question, then the query. Name the columns you show, give calculated columns an alias, and useORDER BYwherever order matters. - Answer: (1) Which active walks do we offer, cheapest first? (2) What are our three cheapest walks? (3) Which walks take under 3 hours? (4) Which moderate walks do we have, by price? (5) Which walks cost from R500 to R700? (6) Which easy or moderate walks take 3 hours or less? (7) Which walks mention Table Mountain in their area? (8) A visitor types "gorge" in the search box: which walks match, in any capitals? (9) In which areas do we walk, each listed once?
- Answer: (10) What does each walk cost per person for a group of 4 or more, and in total for 4, with 10% off rounded to the rand? (11) Which walks give the most metres of climbing per rand, to two decimals? (12) The website shows walks two at a time in name order: what is on page 2? (13) Who are our guides? (14) A staff contact list showing "name (role)" and the phone, with a hyphen where there is none. (15) Which staff have no phone number? (16) When were the staff accounts created, and how long ago? (17) What day of the week is 5 December 2026, and how many days from today?
- Question 18: Mandla wants to put the Lion's Head up to R690. Write it as a rehearsal:
BEGIN;, theUPDATEwithupdated_at = now()andRETURNING, thenROLLBACK;, with a comment explaining how to make it real. The whole file must leave the data unchanged. - Run the whole file with
-v ON_ERROR_STOP=1 -f sql/queries.sqland check the answers by eye against the walks table. Question 3 should give 2 rows, question 6 gives 3, question 7 gives 4 (one of them is at Kirstenbosch: explain why in your notes), and question 15 gives 1. Then run question 1 again to confirm the Lion's Head is still R650.
What you produce: sql/queries.sql with 18 commented business questions and tested answers, which can be run at any time without changing the data.
Time: 1 hour 45 minutes.
Task 5: Make safe changes, write the README and commit
- Practise the safe-change habit from the lesson on the worked example: the Skeleton Gorge ladders close for a month, so take that walk off the website and lower the Platteklip price by R50. Write each
WHEREclause as aSELECTfirst, then make both changes in one transaction withRETURNING, check the command tags andCOMMIT. Confirm with question 1 from your queries file that Skeleton Gorge has gone and Platteklip costs R800. - Now make the classic mistake on purpose, safely:
BEGIN;, thenUPDATE walks SET price_zar = 500;with noWHERE. Read the command tag, look at the prices, andROLLBACK;. Do the same withDELETE FROM users;. Record both command tags in your notes. - Put the data back as the contract has it by rebuilding with
schema.sqlandseed.sql, and check that Skeleton Gorge is active at R900 again. Note in one sentence why this rebuild is safe now and would not be on a live database. - Write
README.mdfor the project: what the Walk Office database is, what each SQL file does, what you need (PostgreSQL 18, thewalks_approle andmandlas_walksdatabase from Module 0), and the exact commands to rebuild the database and run the queries. - Check
git status: the three SQL files, the README and your notes should be listed, and no.pgpassor password anywhere. Commit with a clear message such as "Create walks and users tables, seed data and business queries". If your repository is on GitHub, push the branch withgit push -u origin module-1, open a pull request, read through the changes as a reviewer would, and merge it. Otherwise mergemodule-1intomainlocally.
What you produce: a merged, committed Module 1 milestone: sql/schema.sql, sql/seed.sql, sql/queries.sql, README.md and docs/module-1-notes.md, and a database that matches the contract.
How to check: in a fresh terminal, the two commands in your README rebuild the database and run every query without an error, and git log --oneline shows your commit on main.
Time: 1 hour 15 minutes.
Show the model answer
Task 1: Set up the project and find your way around psql
Your notes should record the database (mandlas_walks), the role (walks_app), the host (localhost) and the port (5432 unless you changed it in Module 0), but never the password. After ALTER DATABASE and a fresh connection, SHOW timezone; answers Africa/Johannesburg, and now() ends in +02: South African time is two hours ahead of UTC, all year.
The experiments give these results, and good explanations say why:
| Statement | Result | Why |
|---|---|---|
0.1::float8 + 0.2::float8 | 0.30000000000000004 | Floating point cannot hold 0.1 or 0.2 exactly, so never use it for money. |
0.1::numeric + 0.2::numeric | 0.3 | numeric is exact decimal arithmetic. |
7 / 2 and 7 / 2.0 | 3 and 3.5000000000000000 | Integer divided by integer drops the fraction. One numeric side keeps it. |
round(612.5), round(650 * 0.9) | 613, 585 | Numeric rounding takes halves away from zero. 650 less 10% is exactly 585. |
1234.5::numeric(4,1) | ERROR: numeric field overflow | Four digits with one after the point allows at most 999.9. |
timestamptz '2026-12-05 05:00' | 2026-12-05 05:00:00+02 | Read in the session zone, Africa/Johannesburg. |
... AT TIME ZONE 'Europe/London' | 2026-12-05 03:00:00 | The same moment on a London clock, two hours behind in December. |
NULL = NULL, NULL IS NULL | NULL (blank), t | Comparing unknowns is unknown. IS NULL is the test that works. |
true OR NULL, false AND NULL | t, f | The answer does not depend on the unknown part. |
A sensible meta-command list includes \d (describe a table), \dt (list tables), \x (expanded display), \i (run a file), \conninfo, \h (SQL syntax help), \e and \q.
Common mistakes and fixes:
- "psql: error: connection to server ... failed: FATAL: password authentication failed". The password is wrong, or the line in
~/.pgpassdoes not match. If the message says "Peer authentication failed" instead, you left out-h localhost, so psql tried a local socket connection as your Linux user. Use the full command from the lesson. - The time zone did not change.
ALTER DATABASE ... SETapplies to new connections only. Quit with\qand connect again. - "must be owner of database mandlas_walks". You are connected as another role. Check
\conninfoand connect aswalks_app. - A password in the notes or in
.pgpassinside the project. Keep.pgpassin your home folder only, and keep passwords out of the repository.
Task 2: Write sql/schema.sql and test every constraint
The complete file, as tested:
-- Walk Office database, Module 1: the walks and users tables.
-- Run with: psql -h localhost -U walks_app -d mandlas_walks -f sql/schema.sql
-- Module 2 adds the other tables. Running this file again starts afresh.
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS walks;
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()
);
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
email text NOT NULL UNIQUE CHECK (email = lower(email)),
-- A placeholder until Module 8 stores real password hashes.
password text NOT NULL,
role text NOT NULL CHECK (role IN ('admin', 'office', 'guide')),
phone text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
Running it the first time prints two notices that the tables did not exist yet, then succeeds. The second run prints no notices, which proves the file is repeatable:
$ psql -h localhost -U walks_app -d mandlas_walks -1 -v ON_ERROR_STOP=1 \
-f sql/schema.sql
DROP TABLE
DROP TABLE
CREATE TABLE
CREATE TABLE
The order of the two DROP statements does not matter yet, because no foreign key joins the tables. In Module 2 it will: tables that refer to others are dropped first.
Your notes' table of broken rules should hold these first lines (from version 16 with \set VERBOSITY terse, which hides the DETAIL lines):
| Attempt | Error | Caught by |
|---|---|---|
difficulty 'Easy' | new row for relation "walks" violates check constraint "walks_difficulty_check" | The difficulty check (text comparison is case-sensitive) |
| price 0 | ... violates check constraint "walks_price_zar_check" | CHECK (price_zar > 0) |
| no name | null value in column "name" of relation "walks" violates not-null constraint | NOT NULL on name |
| hand-typed id | cannot insert a non-DEFAULT value into column "id" | GENERATED ALWAYS AS IDENTITY |
| distance 1234.5 | numeric field overflow | The type numeric(4,1) itself |
max_group 9 | ... violates check constraint "walks_max_group_check" | CHECK (max_group BETWEEN 1 AND 8) |
role 'manager' | new row for relation "users" violates check constraint "users_role_check" | The role check |
email 'Test@mandlaswalks.co.za' | ... violates check constraint "users_email_check" | CHECK (email = lower(email)) |
For the foreign key, a departure for a missing walk fails with "insert or update on table "departures_demo" violates foreign key constraint "departures_demo_walk_id_fkey"" and "Key (walk_id)=(42) is not present in table "walks"". After Task 3, with two Pipe Track departures, RESTRICT refuses the delete ("Key (id)=(3) is still referenced from table "departures_demo""), and CASCADE reports DELETE 1 while silently emptying departures_demo too. Your note should say which is safer for business records, and why: RESTRICT, because history is never lost by accident.
Common mistakes and fixes:
- A comma after the last column, before the closing bracket. PostgreSQL reports "syntax error at or near ")"". Remove the comma.
CHECK (role IN ("admin", "office", "guide"))with double quotes. Double quotes mean names, so PostgreSQL says column "admin" does not exist. Text takes single quotes.serialorintegerids. Usebigint GENERATED ALWAYS AS IDENTITY, as the contract and lesson do.floatorrealfor distances or prices. Usenumeric(4,1)for distance andintegerwhole rand for prices.timestampinstead oftimestamptz.\dmust say "timestamp with time zone".- Every statement after the first error says "current transaction is aborted". That is expected inside
BEGIN. TypeROLLBACK;before the next attempt.
Task 3: Write sql/seed.sql with the walks and the staff
The complete file. The emails and phone numbers are invented (any lower-case mandlaswalks.co.za addresses and 555 numbers will do), and your summaries may differ:
-- Walk Office database, Module 1: the six walks and the four staff users.
-- Run after schema.sql. All people are invented.
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.'),
('pipe-track', 'The Pipe Track',
'Table Mountain National Park', 6, 2.5, 120, 'easy', 450,
-33.944, 18.394,
'A gentle path along the slopes above Camps Bay, with sea views '
'all the way.'),
('skeleton-gorge', 'Skeleton Gorge from Kirstenbosch',
'Kirstenbosch and Table Mountain', 7, 4.5, 720, 'hard', 900,
-33.988, 18.432,
'Ladders and boulders through a shady forest gorge, up to the '
'reservoirs on the back table.'),
('silvermine', 'Silvermine Reservoir and Elephant''s Eye',
'Silvermine', 8, 3.5, 300, 'moderate', 600,
-34.077, 18.418,
'Fynbos slopes to a cave with views over the Constantia valley '
'and False Bay, ending at the reservoir.'),
('cape-point', 'Cape Point lighthouse and Diaz Beach',
'Cape of Good Hope', 4, 2, 150, 'easy', 550,
-34.355, 18.497,
'Up to the old lighthouse and down the steps to a wild beach '
'below the cliffs.')
RETURNING id, slug, price_zar;
INSERT INTO users (name, email, password, role, phone)
VALUES
('Mandla Dube', 'mandla@mandlaswalks.co.za', 'not-set', 'admin',
'082 555 0101'),
('Zanele Khumalo', 'zanele@mandlaswalks.co.za', 'not-set', 'office',
'021 555 0142'),
('Sipho Ndlovu', 'sipho@mandlaswalks.co.za', 'not-set', 'guide',
'083 555 0177'),
('Aisha Patel', 'aisha@mandlaswalks.co.za', 'not-set', 'guide',
NULL)
RETURNING id, name, role;
$ psql -h localhost -U walks_app -d mandlas_walks -1 -v ON_ERROR_STOP=1 \
-f sql/schema.sql -f sql/seed.sql
DROP TABLE
DROP TABLE
CREATE TABLE
CREATE TABLE
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
id | name | role
----+----------------+--------
1 | Mandla Dube | admin
2 | Zanele Khumalo | office
3 | Sipho Ndlovu | guide
4 | Aisha Patel | guide
(4 rows)
INSERT 0 4
The ids start at 1 after every rebuild, because dropping a table drops its identity sequence too. The check against the contract shows numeric columns with their full scale, which is the same value written differently: 6 shows as 6.0 and -33.936 as -33.93600.
id | slug | distance_km | duration_hours | ascent_m | difficulty
----+----------------+-------------+----------------+----------+------------
1 | lions-head | 5.5 | 3.0 | 370 | moderate
2 | platteklip | 6.0 | 4.0 | 750 | hard
3 | pipe-track | 6.0 | 2.5 | 120 | easy
4 | skeleton-gorge | 7.0 | 4.5 | 720 | hard
5 | silvermine | 8.0 | 3.5 | 300 | moderate
6 | cape-point | 4.0 | 2.0 | 150 | easy
(6 rows)
(The price and start point columns are left off here to fit the page.) Running the seed file again on its own fails at once, and with -1 nothing is inserted at all:
$ psql -h localhost -U walks_app -d mandlas_walks -1 -v ON_ERROR_STOP=1 \
-f sql/seed.sql
psql:sql/seed.sql:38: ERROR: duplicate key value violates unique constraint
"walks_slug_key"
DETAIL: Key (slug)=(lions-head) already exists.
The unique slug protects the data from a double load, which is exactly its job. Without the unique constraint you would now have twelve walks. The fix is to rebuild with both files, never to remove the constraint.
Common mistakes and fixes:
- "syntax error at or near "s"" in the walks insert. A single apostrophe in Lion's or Elephant's ended the text early. Double it:
'Lion''s Head sunrise'. - "INSERT has more expressions than target columns". A value is missing from the column list, or a row has an extra value. Count both.
- Aisha's phone stored as
'NULL'in quotes. That is the four-letter word NULL, not a missing value, and question 15 will not find her. WriteNULLwithout quotes. - Coordinates swapped. Latitude comes first and is negative for South Africa (about -34), longitude second (about 18).
Task 4: Answer Mandla's questions in sql/queries.sql
The complete file, as tested. Your queries may be worded differently and still be right, as long as they give the same rows:
-- Walk Office database, Module 1: business questions answered in SQL.
-- Run after schema.sql and seed.sql. This file changes nothing:
-- the one price change is rehearsed inside a transaction and rolled back.
-- 1. Which walks do we offer, cheapest first?
SELECT name, difficulty, price_zar
FROM walks
WHERE is_active
ORDER BY price_zar, name;
-- 2. What are our three cheapest walks?
SELECT name, price_zar
FROM walks
ORDER BY price_zar
LIMIT 3;
-- 3. Which walks take under 3 hours?
SELECT name, duration_hours
FROM walks
WHERE duration_hours < 3
ORDER BY duration_hours;
-- 4. Which moderate walks do we have, by price?
SELECT name, price_zar
FROM walks
WHERE difficulty = 'moderate'
ORDER BY price_zar;
-- 5. Which walks cost from R500 to R700 per person?
SELECT name, price_zar
FROM walks
WHERE price_zar BETWEEN 500 AND 700
ORDER BY price_zar;
-- 6. Which easy or moderate walks take 3 hours or less?
SELECT name, difficulty, duration_hours
FROM walks
WHERE difficulty IN ('easy', 'moderate')
AND duration_hours <= 3
ORDER BY duration_hours;
-- 7. Which walks mention Table Mountain in their area?
SELECT name, area
FROM walks
WHERE area LIKE '%Table Mountain%'
ORDER BY name;
-- 8. A visitor searches for "gorge", in any capitals.
SELECT slug, name
FROM walks
WHERE name ILIKE '%gorge%';
-- 9. In which areas do we walk?
SELECT DISTINCT area
FROM walks
ORDER BY area;
-- 10. What does each walk cost per person for a group of 4 or more,
-- and in total for a group of 4? (10% off, rounded to the rand)
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;
-- 11. Which walks give the most climbing for the money?
SELECT name,
ascent_m,
price_zar,
round(ascent_m / price_zar::numeric, 2) AS metres_per_rand
FROM walks
ORDER BY metres_per_rand DESC, name;
-- 12. The walks list for the website, two at a time: page 2.
SELECT slug, name
FROM walks
ORDER BY name
LIMIT 2 OFFSET 2;
-- 13. Who are our guides?
SELECT name, email, phone
FROM users
WHERE role = 'guide'
ORDER BY name;
-- 14. A staff contact list, with a dash where a phone number is missing.
SELECT name || ' (' || role || ')' AS staff_member,
COALESCE(phone, '-') AS phone
FROM users
ORDER BY name;
-- 15. Which staff have no phone number recorded?
SELECT name
FROM users
WHERE phone IS NULL;
-- 16. When were the staff accounts created, in South African time,
-- and how long ago?
SELECT name,
date_trunc('minute', created_at) AS created,
age(now(), created_at) AS how_long_ago
FROM users
ORDER BY created_at;
-- 17. Saturday 5 December 2026: what day of the week, and how many days
-- from today?
SELECT extract(isodow FROM date '2026-12-05') AS iso_day_of_week,
date '2026-12-05' - current_date AS days_from_today;
-- 18. Mandla puts Lion's Head up to R690. Rehearse it safely:
BEGIN;
UPDATE walks
SET price_zar = 690,
updated_at = now()
WHERE slug = 'lions-head'
RETURNING slug, price_zar;
ROLLBACK;
-- To make the change for real, run the same UPDATE with COMMIT instead.
Key results to compare with yours: question 3 gives Cape Point (2.0 hours) and the Pipe Track (2.5). Question 6 gives those two and Lion's Head at exactly 3.0, which <= 3 includes and < 3 would not. Question 7 gives four walks, because Skeleton Gorge's area, "Kirstenbosch and Table Mountain", also contains the words: LIKE '%...%' matches anywhere in the text. Question 10 gives R405, R495, R540, R585, R765 and R810 per person, and R2,340 for four on Lion's Head. Question 11 puts Platteklip first at 0.88 metres per rand, and question 12 gives Platteklip and Silvermine.
staff_member | phone
-------------------------+--------------
Aisha Patel (guide) | -
Mandla Dube (admin) | 082 555 0101
Sipho Ndlovu (guide) | 083 555 0177
Zanele Khumalo (office) | 021 555 0142
(4 rows)
name
-------------
Aisha Patel
(1 row)
iso_day_of_week | days_from_today
-----------------+-----------------
6 | 33
(1 row)
BEGIN
slug | price_zar
------------+-----------
lions-head | 690
(1 row)
UPDATE 1
ROLLBACK
The day of the week is 6, a Saturday. The days from today depend on when you run it (33 here, run on 2 November 2026), and so do the creation times in question 16, which show the moment you last rebuilt the database. After the file runs, the Lion's Head still costs R650.
Common mistakes and fixes:
- Question 8 with
LIKE '%gorge%'. It finds nothing, because both names have a capital G. UseILIKE. - Question 11 gives zeros.
ascent_m / price_zardivides integers and drops the fraction. Cast one side:price_zar::numeric. - Question 14 shows a blank name for Aisha. You joined the phone with
||, so the whole result became NULL. UseCOALESCE(phone, '-')in its own column, orconcat. - Question 15 written
WHERE phone = NULL. It always gives 0 rows. UseIS NULL. - Question 12 without
ORDER BY. "Page 2" is then any two walks. Pages need a fixed order. - The rehearsal ends with
COMMIT. The price then really changes, and the file is no longer safe to run. Rebuild the database and change it toROLLBACK.
Task 5: Make safe changes, write the README and commit
The safe changes follow the worked example in the lesson exactly: two SELECT statements to check the WHERE clauses, BEGIN, two updates each reporting UPDATE 1, and COMMIT. Question 1 then lists five walks, with Platteklip at R800. The deliberate mistakes report UPDATE 6 and DELETE 4, the whole table each time, and ROLLBACK undoes them. Rebuilding is safe here because the files hold everything the database holds. On a live database, rebuilding would wipe every booking made since, so there you would reverse the changes with two more updates.
A model README:
# Walk Office database (walks-sql)
The PostgreSQL database for the Walk Office, the back end of Mandla's
Mountain Walks (an invented business), built in WEB-301 Modules 1 and 2.
## Files
- `sql/schema.sql` creates the tables. It drops them first, so it always
gives a clean, empty design. Module 1: `walks` and `users`.
- `sql/seed.sql` inserts the starting data: six walks and four staff users.
- `sql/queries.sql` answers business questions. It changes nothing.
## You need
PostgreSQL 18 with the login role `walks_app` and the database
`mandlas_walks` it owns (WEB-301 Module 0), and psql.
## Rebuild the database
This deletes everything in the two tables and starts again:
```bash
psql -h localhost -U walks_app -d mandlas_walks -1 -v ON_ERROR_STOP=1 \
-f sql/schema.sql -f sql/seed.sql
```
## Run the business questions
```bash
psql -h localhost -U walks_app -d mandlas_walks -v ON_ERROR_STOP=1 \
-f sql/queries.sql
```
$ git status --short
A README.md
A docs/module-1-notes.md
A sql/queries.sql
A sql/schema.sql
A sql/seed.sql
$ git commit -m "Create walks and users tables, seed data and business queries"
[module-1 541af6c] Create walks and users tables, seed data and business queries
5 files changed, 243 insertions(+)
$ git push -u origin module-1
(The status shows the files after git add .. The commit's "create mode" lines and the push output are left out here, and your commit id and line count will differ.) On GitHub, open the pull request from module-1 into main, read the changes file by file, and merge it. Then git switch main and git pull, so your local main has the merge. Without GitHub, git switch main and git merge module-1 do the same locally.
Common mistakes and fixes:
- Committing straight to
main. Create the branch in Task 1 next time. To fix it now,git switch -c module-1keeps your commit on a new branch, and you can still open a pull request. - A
.pgpassfile or password in the repository. Remove it, change thewalks_apppassword (connected aswalks_app, type\passwordin psql), and add the file name to.gitignore. A password that has been pushed must be treated as public. - The README's rebuild command does not work when pasted. Test it in a fresh terminal, from the project folder, exactly as written.