Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 2

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

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:

  1. design a reviews table with suitable types and constraints, and see each constraint reject a bad row;
  2. evolve the table with ALTER TABLE;
  3. preview an UPDATE and a DELETE before running it, and undo a whole batch with a transaction;
  4. 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:

SQL · store=#
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)
);
Expected output
CREATE TABLE
psql · \d reviews
                   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:

SQL · store=#
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;
Illustrative output (only created_at differs: it shows the day you run it)
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:

SQL · rating outside 1–5
INSERT INTO reviews (id, product_id, reviewer, rating)
VALUES (4, 4, '[email protected]', 9);
Illustrative output (only the date differs: it is the day you run it)
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).
SQL · review of a product that does not exist
INSERT INTO reviews (id, product_id, reviewer, rating)
VALUES (5, 999, '[email protected]', 3);
Expected output
ERROR:  insert or update on table "reviews" violates foreign key constraint "product_fk"
DETAIL:  Key (product_id)=(999) is not present in table "products".
SQL · required column omitted
INSERT INTO reviews (id, product_id, reviewer)
VALUES (6, 6, '[email protected]');
Illustrative output (only the date differs: it is the day you run it)
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).
SQL · Clara reviews the same monitor twice
INSERT INTO reviews (id, product_id, reviewer, rating)
VALUES (7, 4, '[email protected]', 3);
Expected output
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:

SQL · store=#
ALTER TABLE reviews
  ADD COLUMN verified boolean NOT NULL DEFAULT false;

SELECT reviewer, rating, verified FROM reviews ORDER BY id;
Expected output
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:

SQL · preview first
SELECT id, rating, verified FROM reviews WHERE reviewer = '[email protected]';
Expected output
 id | rating | verified 
----+--------+----------
  2 |      4 | f
(1 row)
SQL · then change exactly those rows
UPDATE reviews SET rating = 5, verified = true
WHERE reviewer = '[email protected]';

SELECT reviewer, rating, verified FROM reviews ORDER BY id;
Expected output
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:

SQL · a missing WHERE, safely rehearsed
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;
Expected output
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:

SQL · store=#
SELECT id, reviewer FROM reviews WHERE id = 3;
DELETE FROM reviews WHERE id = 3;
SELECT count(*) AS remaining FROM reviews;
Expected output
 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:

SQL · store=#
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;
Expected output
SELECT 2
 backup_rows 
-------------
           2
(1 row)

TRUNCATE TABLE
 backup_rows 
-------------
           0
(1 row)

DROP TABLE

CREATE 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:

SQL · store=#
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;
Expected output
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:

SQL · store=#
\dv
SELECT month, revenue FROM monthly_revenue
WHERE revenue >= 300
ORDER BY month;
Expected output
             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

Practice check · 3 questions

Writing data

Three decisions from the write path.

Q1. You must empty a staging table completely and as fast as possible for the next reload, while keeping the table and its schema. Which statement fits best?
Q2. Before running UPDATE reviews SET rating = rating + 1 WHERE product_id = 4, what is the cheapest reliable check of which rows it will touch?
Q3. reviews.product_id has a foreign key to products.id. What happens when you insert a review for product 999, which does not exist?
Practice only: not graded, not saved, not evidence.

11. Apply it

Round off the practice project:

  1. Re-create reviews with id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, insert without naming id, and inspect how \d shows the default.
  2. Add CHECK (status IN ('new', 'paid', 'shipped', 'cancelled')) to orders with ALTER TABLE, then try inserting an order with status pending.
  3. 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:

  1. Name the four kinds of clause in a table contract, and what each guarantees.
  2. Which rule did each of the four failed inserts break, and what did each error message tell you?
  3. Describe the preview habit for UPDATE and DELETE, and how BEGIN and ROLLBACK make a missing WHERE survivable.
  4. 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.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check