Tables, Views and Changing Data Safely
Create a reviews table with types, keys and constraints, watch bad rows bounce off, preview UPDATE and DELETE before running them, and publish a report as a view.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: declare the table and its rules
- Step 2: insert good rows
- Step 3: watch bad rows bounce
- Step 4: evolve the table with ALTER
- Step 5: UPDATE with a preview and an undo
- Step 6: DELETE, TRUNCATE and DROP
- Step 7: publish the report as a view
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of SQL Fundamentals
- Tables, Rows and a First Session in psql Concept · 20 min
- Filtering, Sorting and the NULL Trap Worked example · 25 min
- Joins and Subqueries Without Multiplying Rows Lab · 30 min
- Turning Rows into Business Metrics Lab · 25 min
- Tables, Views and Changing Data Safely Lab · 25 min
- Check: Answer Questions About an Unseen Schema Knowledge check · 10 questions
What you will learn
- Create tables with suitable data types and constraints, and insert, update and delete rows without touching unintended data.
01. Goal and setup
So far you only read the store. This lab gives it a new feature — product reviews — and with it the two halves of writing SQL with confidence: declared rules that make the database refuse rows that break them, and safe habits for changing rows that already exist. You will:
- design a
reviewstable with suitable types and constraints, and see each constraint reject a bad row; - evolve the table with
ALTER TABLE; - preview an
UPDATEand aDELETEbefore running it, and undo a whole batch with a transaction; - publish the revenue report as a view.
You need: the store database from the joins lesson, connected in psql. Commands below were run on PostgreSQL 17.12; other recent versions behave the same way.
02. Step 1: declare the table and its rules
A table definition is a contract with four kinds of clause. Types (integer, text, date) say what shape each column's values have. NOT NULL says a value is mandatory. Keys and uniqueness identify rows. CHECK states a rule the value itself must satisfy. Write the contract once and every future program inherits it:
CREATE TABLE reviews (
id integer NOT NULL,
product_id integer NOT NULL,
reviewer text NOT NULL,
rating integer NOT NULL CHECK (rating BETWEEN 1 AND 5),
body text,
created_at date NOT NULL DEFAULT CURRENT_DATE,
PRIMARY KEY (id),
CONSTRAINT product_fk
FOREIGN KEY (product_id) REFERENCES products(id),
CONSTRAINT one_review_per_product
UNIQUE (product_id, reviewer)
);CREATE TABLE Table "public.reviews"
Column | Type | Collation | Nullable | Default
------------+---------+-----------+----------+--------------
id | integer | | not null |
product_id | integer | | not null |
reviewer | text | | not null |
rating | integer | | not null |
body | text | | |
created_at | date | | not null | CURRENT_DATE
Indexes:
"reviews_pkey" PRIMARY KEY, btree (id)
"one_review_per_product" UNIQUE CONSTRAINT, btree (product_id, reviewer)
Check constraints:
"reviews_rating_check" CHECK (rating >= 1 AND rating <= 5)
Foreign-key constraints:
"product_fk" FOREIGN KEY (product_id) REFERENCES products(id)Read the description carefully — it is the database playing your contract back to you. Two details are worth noticing. PostgreSQL stored BETWEEN 1 AND 5 as rating >= 1 AND rating <= 5, the same rule in plainer terms. And the unnamed CHECK got an automatic name (reviews_rating_check) which will appear in error messages; the named constraints (product_fk, one_review_per_product) are ours, chosen precisely so that errors are readable.
This table asks the caller to supply id. In production you would more often write id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY and let PostgreSQL assign ids — postponed here so the examples stay explicit. One more production habit: money columns use numeric, as you learned in lesson one, because exact decimals matter more than fast float arithmetic.
03. Step 2: insert good rows
With the contract in place, INSERT adds rows. List the target columns explicitly — that keeps the statement valid when the table later gains columns, and lets DEFAULT do its job for anything you omit. body may be NULL (a rating without prose is fine), and created_at is filled by its default:
INSERT INTO reviews (id, product_id, reviewer, rating, body) VALUES
(1, 4, '[email protected]', 5, 'Crisp panel, great colours.'),
(2, 2, '[email protected]', 4, 'Keys feel lovely; a bit loud.'),
(3, 1, '[email protected]', 5, NULL);
SELECT id, product_id, reviewer, rating, created_at
FROM reviews
ORDER BY id;INSERT 0 3
id | product_id | reviewer | rating | created_at
----+------------+-------------------+--------+------------
1 | 4 | [email protected] | 5 | 2026-11-26
2 | 2 | [email protected] | 4 | 2026-11-26
3 | 1 | [email protected] | 5 | 2026-11-26
(3 rows)04. Step 3: watch bad rows bounce
Now attack your own table on purpose. Each insert below breaks exactly one rule; each error names the constraint that caught it. This is the contract working — the alternative is these rows sitting quietly in your data until a report embarrasses you:
INSERT INTO reviews (id, product_id, reviewer, rating)
VALUES (4, 4, '[email protected]', 9);ERROR: new row for relation "reviews" violates check constraint "reviews_rating_check"
DETAIL: Failing row contains (4, 4, [email protected], 9, null, 2026-11-26).INSERT INTO reviews (id, product_id, reviewer, rating)
VALUES (5, 999, '[email protected]', 3);ERROR: insert or update on table "reviews" violates foreign key constraint "product_fk"
DETAIL: Key (product_id)=(999) is not present in table "products".INSERT INTO reviews (id, product_id, reviewer)
VALUES (6, 6, '[email protected]');ERROR: null value in column "rating" of relation "reviews" violates not-null constraint
DETAIL: Failing row contains (6, 6, [email protected], null, null, 2026-11-26).INSERT INTO reviews (id, product_id, reviewer, rating)
VALUES (7, 4, '[email protected]', 3);ERROR: duplicate key value violates unique constraint "one_review_per_product"
DETAIL: Key (product_id, reviewer)=(4, [email protected]) already exists.Four guards, four clear refusals. Note what the errors have in common: the statement fails, the table is untouched, and the message names the rule. In application code you catch these errors and turn them into user-facing messages ("you already reviewed this product") — the constraint stays the source of truth. One caveat from lesson two: a CHECK only rejects rows it can prove false, so pair NOT NULL with CHECK (rating >= 0)-style rules rather than expecting a comparison with NULL to catch missing values.
05. Step 4: evolve the table with ALTER
Requirements change, and ALTER TABLE changes tables that already hold data. Add a column and every existing row reads the new default at once. Since PostgreSQL 11 a constant default like false is stored once in the catalogue, so the table is not rewritten; the statement still takes a short exclusive lock on the table, which matters on a busy production table:
ALTER TABLE reviews
ADD COLUMN verified boolean NOT NULL DEFAULT false;
SELECT reviewer, rating, verified FROM reviews ORDER BY id;ALTER TABLE
reviewer | rating | verified
-------------------+--------+----------
[email protected] | 5 | f
[email protected] | 4 | f
[email protected] | 5 | f
(3 rows)Other common shapes: DROP COLUMN removes a column, ALTER COLUMN ... TYPE text changes a type (PostgreSQL converts where it can), and ADD CONSTRAINT adds a rule later — though adding a constraint fails if existing rows already break it, which is the safety you want. In a real project these schema changes are versioned in migration files rather than typed by hand; the schema migrations skill builds that workflow.
06. Step 5: UPDATE with a preview and an undo
UPDATE ... SET rewrites column values in the rows its WHERE matches — and in only those rows. Ben verified his purchase and his rating deserves a nudge; but first, run the exact WHERE under SELECT to see the blast radius before committing to it:
SELECT id, rating, verified FROM reviews WHERE reviewer = '[email protected]'; id | rating | verified
----+--------+----------
2 | 4 | f
(1 row)UPDATE reviews SET rating = 5, verified = true
WHERE reviewer = '[email protected]';
SELECT reviewer, rating, verified FROM reviews ORDER BY id;UPDATE 1
reviewer | rating | verified
-------------------+--------+----------
[email protected] | 5 | f
[email protected] | 5 | t
[email protected] | 5 | f
(3 rows)UPDATE 1 is psql telling you one row changed. For anything bigger than a single known row, add a second safety net: a transaction. Everything between BEGIN and COMMIT is provisional; if the result is wrong, ROLLBACK restores the table as if nothing happened. Run an update that forgot its WHERE — on purpose, this once — and watch the damage evaporate:
BEGIN;
UPDATE reviews SET rating = 1;
SELECT min(rating) AS low, max(rating) AS high FROM reviews;
ROLLBACK;
SELECT min(rating) AS low, max(rating) AS high FROM reviews;BEGIN
UPDATE 3
low | high
-----+------
1 | 1
(1 row)
ROLLBACK
low | high
-----+------
5 | 5
(1 row)All three rows dropped to 1 inside the transaction, and the world outside saw nothing. Transactions are a large topic of their own — the transactions and isolation skill takes them further; the habit to take away today is rehearse destructive changes.
07. Step 6: DELETE, TRUNCATE and DROP
DELETE removes the rows its WHERE matches, and takes the same preview discipline as UPDATE. Amara asked for her review to be withdrawn:
SELECT id, reviewer FROM reviews WHERE id = 3;
DELETE FROM reviews WHERE id = 3;
SELECT count(*) AS remaining FROM reviews; id | reviewer
----+-------------------
3 | [email protected]
(1 row)
DELETE 1
remaining
-----------
2
(1 row)Three statements remove data, with different reach. DELETE FROM t WHERE ... removes selected rows, checking row constraints and firing triggers. TRUNCATE removes every row at once by deallocating table pages — fast, and in PostgreSQL it is transaction-safe (rolls back cleanly on ROLLBACK), but it has three catches. It takes an ACCESS EXCLUSIVE lock, so every other query on the table waits. It skips row-level delete triggers. And a transaction that started earlier and reads the table afterwards may suddenly see it as empty. DROP TABLE removes the table itself — rows, columns, constraints, everything. Try TRUNCATE on a throwaway copy so nothing of value is at risk:
CREATE TABLE reviews_backup AS TABLE reviews;
SELECT count(*) AS backup_rows FROM reviews_backup;
TRUNCATE reviews_backup;
SELECT count(*) AS backup_rows FROM reviews_backup;
DROP TABLE reviews_backup;SELECT 2
backup_rows
-------------
2
(1 row)
TRUNCATE TABLE
backup_rows
-------------
0
(1 row)
DROP TABLECREATE TABLE ... AS TABLE ... copies rows into a new table — here a two-row backup, then empty, then gone. In practice, reach for DELETE for targeted removal, TRUNCATE to reset a table you are about to reload, and DROP only when the table itself is obsolete.
08. Step 7: publish the report as a view
The monthly-revenue query from the metrics lesson is long, and colleagues will want it often. A view is a saved query with a name: it stores no rows, but every query against it runs the definition fresh, so the numbers can never go stale relative to the tables:
CREATE VIEW monthly_revenue AS
SELECT date_trunc('month', o.created_at)::date AS month,
sum(i.quantity * i.unit_price) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY 1;
SELECT * FROM monthly_revenue ORDER BY month;CREATE VIEW
month | revenue
------------+---------
2026-06-01 | 48.80
2026-07-01 | 375.50
2026-08-01 | 134.00
2026-09-01 | 370.40
(4 rows)Query it, filter it, sort it — a view behaves like a table for reading. \dv lists views alongside \dt for tables, and the report you built once now has a stable name the whole team can rely on:
\dv
SELECT month, revenue FROM monthly_revenue
WHERE revenue >= 300
ORDER BY month; List of relations
Schema | Name | Type | Owner
--------+-----------------+------+----------
public | monthly_revenue | view | postgres
(1 row)
month | revenue
------------+---------
2026-07-01 | 375.50
2026-09-01 | 370.40
(2 rows)When a view outlives its purpose, DROP VIEW monthly_revenue removes the definition (and only the definition — the underlying rows are untouched). Keep the view; the final practice project asks for exactly such a published report.
09. Troubleshooting
10. Check your understanding
11. Apply it
Round off the practice project:
- Re-create
reviewswithid integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, insert without namingid, and inspect how\dshows the default. - Add
CHECK (status IN ('new', 'paid', 'shipped', 'cancelled'))toorderswithALTER TABLE, then try inserting an order with statuspending. - Publish your strongest report from the metrics lesson as a view (the practice asks for a grouped, HAVING-filtered one), query it twice around an INSERT, and watch the numbers follow.
From here, the road continues with relational data modelling for designing whole schemas, schema migrations for changing them in production, and data access with SQLAlchemy for calling all of this from Python.
12. Review prompt
Without looking back:
- Name the four kinds of clause in a table contract, and what each guarantees.
- Which rule did each of the four failed inserts break, and what did each error message tell you?
- Describe the preview habit for UPDATE and DELETE, and how BEGIN and ROLLBACK make a missing WHERE survivable.
- What do DELETE, TRUNCATE and DROP each remove, and what does a view store?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.