Sub topic 1
Recap: Single-Table UPDATE and DELETE
Every join-based change in PostgreSQL is built on the single-table forms of UPDATE and DELETE. This chapter reviews how those two statements pick rows and change them. It also shows where a plain WHERE clause stops being enough. The later chapters add UPDATE ... FROM and DELETE ... USING to cover that gap.
Prerequisites
You should already be comfortable with the following:
- Basic
SELECT,WHERE, andINNER JOINsyntax. - Table aliases, primary keys, and foreign keys.
- Running statements in
psqlor another PostgreSQL client. - Having written a simple
UPDATEorDELETEbefore. This chapter is a review, not an introduction.
The schema used in this tutorial
The examples in this tutorial share four tables. Create them once and reuse them.
CREATE TABLE customers (
id integer PRIMARY KEY,
name text NOT NULL,
status text NOT NULL DEFAULT 'active'
);
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers (id),
total numeric(10,2) NOT NULL,
status text NOT NULL DEFAULT 'open'
);
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2) NOT NULL
);
CREATE TABLE price_updates (
product_id integer NOT NULL REFERENCES products (id),
new_price numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);Add a few rows so you can see the effect of each statement:
INSERT INTO customers (id, name, status) VALUES
(1, 'Ada', 'active'),
(2, 'Ben', 'closed'),
(3, 'Cleo', 'active');
INSERT INTO products (id, name, price) VALUES
(1, 'Pen', 2.50),
(2, 'Notebook', 4.00),
(3, 'Stapler', 9.99);
INSERT INTO orders (id, customer_id, total, status) VALUES
(1, 1, 25.00, 'open'),
(2, 2, 40.00, 'open'),
(3, 2, 12.50, 'shipped'),
(4, 3, 8.00, 'open');How UPDATE works
The general form is:
UPDATE table_name [ [AS] alias ]
SET column = expression [, column = expression ...]
[ WHERE condition ];PostgreSQL reads each row of the target table and tests it against the WHERE condition. For every row where the condition is true, it computes the SET expressions and writes a new version of that row. Rows where the condition is false or NULL are left alone. The server then reports how many rows changed, for example UPDATE 1.
UPDATE products
SET price = price * 1.10
WHERE name = 'Pen';The SET expression can refer to the row's own columns. Here price on the right side is the old value. Because the column is numeric(10,2), the result 2.75 is rounded to two decimal places.
You can set several columns in one statement:
UPDATE customers
SET status = 'closed',
name = upper(name)
WHERE id = 3;Right-hand sides see the old row
Every expression in SET is evaluated against the row as it was before the statement changed it. Assignments do not see each other's results. This makes a swap work without a temporary variable:
CREATE TEMP TABLE swap_demo (a integer, b integer);
INSERT INTO swap_demo VALUES (1, 2);
UPDATE swap_demo SET a = b, b = a;
SELECT a, b FROM swap_demo; -- returns 2, 1This rule matters later. With UPDATE ... FROM, the same old-row rule applies to the target table's columns.
How DELETE works
The form is shorter:
DELETE FROM table_name [ [AS] alias ]
[ WHERE condition ];PostgreSQL tests each row against the condition and removes the rows where it is true. The server reports DELETE n.
DELETE FROM orders
WHERE status = 'shipped';After this statement, order 3 is gone and the other three orders remain.
What "delete" and "update" mean internally
PostgreSQL uses multiversion concurrency control (MVCC). An UPDATE does not overwrite a row in place. It marks the old row version as expired and writes a new version. A DELETE only marks the current version as expired. The old versions stay on disk until VACUUM reclaims them. Two consequences follow:
- Other sessions keep seeing the old data until your transaction commits.
- Large updates and deletes leave dead row versions behind, so a big bulk change increases table size until vacuum catches up.
The following diagram shows the steps that both statements share.
Common mistakes in single-table statements
Forgetting WHERE
A statement without WHERE affects every row:
UPDATE orders SET status = 'cancelled'; -- every order
DELETE FROM orders; -- every orderPostgreSQL does not warn you. If you run statements by hand, write the WHERE clause first, or start with a SELECT that uses the same condition.
NULL and three-valued logic
A row is changed only when the condition is true. If a column allows NULL, then WHERE status <> 'closed' skips rows where status is NULL, because NULL <> 'closed' is NULL, not true. Likewise WHERE status = NULL never matches anything. Use IS NULL, IS NOT NULL, or IS DISTINCT FROM when NULL is possible.
Zero rows is not an error
If no row matches, PostgreSQL reports UPDATE 0 or DELETE 0 and succeeds. A typo in a value, such as 'Closed' instead of 'closed', fails silently in this way. Check the row count after every statement, and treat an unexpected 0 as a signal to investigate.
Constraint violations
Deleting a parent row that child rows still reference fails under the default foreign key behavior:
DELETE FROM customers WHERE id = 1;ERROR: update or delete on table "customers" violates foreign key constraint "orders_customer_id_fkey" on table "orders"
DETAIL: Key (id)=(1) is still referenced from table "orders".The whole statement fails, not just the offending row. No rows are deleted. Updates can fail the same way, for example when a NOT NULL or CHECK constraint rejects a new value.
Seeing and undoing what you changed
Two features from the single-table forms carry over unchanged to join-based statements.
RETURNING makes the statement output the affected rows. For UPDATE it returns the new values, and for DELETE it returns the deleted rows:
UPDATE products
SET price = 3.00
WHERE id = 2
RETURNING id, name, price;A transaction lets you inspect a change before you keep it:
BEGIN;
DELETE FROM orders WHERE status = 'open' RETURNING id, total;
ROLLBACK; -- nothing was deletedThe ROLLBACK discards the delete. Replace it with COMMIT to keep the change.
Where a single-table WHERE runs out
The WHERE clause of a single-table statement can only test columns of the target table. Consider this request: cancel every open order that belongs to a closed customer.
The orders table has customer_id but not the customer's status. The status lives in customers. The next table shows what each approach can do with this problem.
| Approach | Works? | Why |
|---|---|---|
| `WHERE c.status = 'closed'` on `orders` alone | No | `c` is not in scope. PostgreSQL reports a missing FROM-clause entry. |
| Look up the closed customer ids by hand, then paste them into `WHERE customer_id IN (2)` | Only for small, one-time jobs | The list goes stale and is error-prone. |
| Put a subquery in `WHERE` | Yes | It works for choosing rows, but it cannot easily copy values from the other table into `SET`. |
| `UPDATE ... FROM` and `DELETE ... USING` | Yes | They join the target to other tables directly. |
The subquery route is covered in a later chapter. The next chapter introduces the join-based forms and explains why PostgreSQL has no UPDATE ... JOIN syntax.
Summary of what to carry forward
UPDATEandDELETEtest every row of one target table againstWHERE, and only rows where the condition is true change.SETexpressions read the old version of the row.- A missing
WHEREclause changes every row, and a mistaken one often changes zero rows without any error. RETURNINGand transactions let you check a change before you commit it.- A plain
WHEREcannot refer to columns of other tables.
Exercise
Using the sample data, write a single statement that adds 1.00 to the price of every product whose name starts with the letter 'S', and shows the product id, name, and new price in its output. What command tag does PostgreSQL report?
Show answer
UPDATE products SET price = price + 1.00 WHERE name LIKE 'S%' RETURNING id, name, price; With the sample data only 'Stapler' matches, so the output has one row (3, Stapler, 10.99) and the command tag is UPDATE 1.
Exercise
A table has a column status that allows NULL. Rows hold the values 'open', 'closed', and NULL. You run DELETE FROM t WHERE status <> 'closed'; Which rows are deleted, and how would you change the condition to delete the 'open' rows and the NULL rows together?
Show answer
Only the 'open' rows are deleted. For NULL rows, status <> 'closed' evaluates to NULL, which is not true, so those rows are skipped. Use WHERE status IS DISTINCT FROM 'closed' to delete both the 'open' rows and the NULL rows.
Exercise
You run DELETE FROM customers WHERE id = 1; and PostgreSQL reports a foreign key violation because order 1 references that customer. After the error, how many rows were deleted from customers and from orders?
Show answer
Zero from both. A failed statement is rolled back as a whole, so neither table changes.