Sub topic 1
Recap: Single-Table `UPDATE` and `DELETE`
Prerequisites
You should know basic SELECT, WHERE, and INNER JOIN syntax. You should also know how to use UPDATE and DELETE on one table, and understand table aliases, primary keys, and foreign keys. The examples assume PostgreSQL and a PostgreSQL client such as psql.
This chapter reviews single-table changes before later chapters add rows from other tables. An UPDATE changes values in existing rows. A DELETE removes rows. In both statements, WHERE decides which rows are affected.
Updating selected rows
The basic form is:
UPDATE table_name
SET column_name = value
WHERE condition;The SET clause gives a new value. The WHERE clause filters the target rows. Without WHERE, PostgreSQL updates every row in the table.
This runnable example creates a temporary table, changes two prices, and displays the changed rows:
CREATE TEMP TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2) NOT NULL
);
INSERT INTO products (id, name, price) VALUES
(1, 'Notebook', 8.50),
(2, 'Pen', 2.00),
(3, 'Mug', 12.00);
UPDATE products
SET price = price * 1.10
WHERE price < 10.00
RETURNING id, name, price;The expression price * 1.10 uses the old value to calculate the new value. Only the notebook and pen match the condition.
RETURNING is a PostgreSQL feature that reports rows changed by UPDATE. It is useful when you need to inspect the result immediately or capture generated values.
Deleting selected rows
The basic form is:
DELETE FROM table_name
WHERE condition;For example, this removes the mug:
DELETE FROM products
WHERE name = 'Mug'
RETURNING id, name;A DELETE removes the complete row, not just selected columns. The condition should usually identify the intended rows by a key or a carefully tested predicate.
Predicting the affected rows
A safe habit is to write a SELECT with the same condition before changing data:
SELECT id, name, price
FROM products
WHERE price < 10.00;If this query returns the rows you expect, the same WHERE condition can usually be used in an UPDATE or DELETE.
The following model shows the flow:
Comparing the two statements
| Statement | Purpose | Result |
|---|---|---|
| `UPDATE` | Change column values | Rows remain, with new values |
| `DELETE` | Remove rows | Matching rows no longer exist |
At this stage, each statement reads one target table. The next step is selecting those target rows based on information stored in another table. PostgreSQL uses UPDATE ... FROM and DELETE ... USING for that job.
Exercise
Write a statement that increases the price of every product costing less than 5.00 by 20%, and returns the changed ids and prices.
Show answer
UPDATE products SET price = price * 1.20 WHERE price < 5.00 RETURNING id, price;