Updating and deleting

Topic 2 of 5 in Changing data11 min readBeginnerFree course

Overview

Data changes: orders ship, prices rise, customers move, stock arrives, records go out of date. UPDATE changes values in existing rows and DELETE removes rows. They’re short commands with an outsized ability to do damage, so this lesson is as much about habits as syntax.

UPDATE

UPDATE names the table, SET gives the new values, and WHERE says which rows to change:

SQL
UPDATE products
SET stock = 25
WHERE id = 3;
Text
UPDATE 1

UPDATE 1 means one row changed. The Decaf House Blend is back in stock.

SET can change several columns at once, and the new value can be calculated from the row’s current values. Two more Glass Teapots arrived and their price went up by a dollar:

SQL
UPDATE products
SET stock = stock + 2,
    price = price + 1.00
WHERE name = 'Glass Teapot';

SELECT name, price, stock FROM products WHERE id IN (3, 11) ORDER BY id;
Text
UPDATE 1
       name        | price | stock 
-------------------+-------+-------
 Decaf House Blend | 11.25 |    25
 Glass Teapot      | 33.00 |     2
(2 rows)

Every expression on the right of = uses the values from before the update, so SET a = b, b = a swaps two columns.

The WHERE clause is everything

UPDATE and DELETE: the WHERE clause is everything. With WHERE: UPDATE products SET price = price * 1.10 WHERE category_id = 2 reports UPDATE 4 — only the teas. Without WHERE: UPDATE products SET price = price * 1.10 reports UPDATE 12 — every product! A safe routine: 1, write it as a SELECT first, such as SELECT * FROM products WHERE category_id = 2; 2, check the rows it returns — the right rows and the right count; 3, run the change in a transaction: BEGIN; UPDATE …; check; COMMIT or ROLLBACK; 4, use RETURNING to see what changed, as in UPDATE … RETURNING id, price. DELETE FROM … WHERE … removes rows and TRUNCATE empties a table at once; neither can be undone after COMMIT.

An UPDATE without WHERE changes every row in the table. There’s no “are you sure?” — PostgreSQL does exactly what you asked. A 10% tea price rise, done right:

SQL
SELECT id, name, price FROM products WHERE category_id = 2 ORDER BY id;
Text
 id |          name          | price 
----+------------------------+-------
  4 | Darjeeling First Flush | 18.00
  5 | Assam Breakfast        |  9.50
  6 | Jasmine Green          | 12.75
  7 | Chamomile Calm         |  8.00
(4 rows)

Four rows, the right ones. Now turn the same WHERE into the UPDATE, and add RETURNING to see the result:

SQL
UPDATE products
SET price = round(price * 1.10, 2)
WHERE category_id = 2
RETURNING id, name, price;
Text
 id |          name          | price 
----+------------------------+-------
  4 | Darjeeling First Flush | 19.80
  5 | Assam Breakfast        | 10.45
  6 | Jasmine Green          | 14.03
  7 | Chamomile Calm         |  8.80
(4 rows)

UPDATE 4

The habit — SELECT first, then change — costs a few seconds and prevents the classic disaster. On real systems, also do it inside a transaction (BEGIN … check … COMMIT or ROLLBACK), which you’ll learn in Transactions.

Updating from other tables

Sometimes the new value — or the decision which rows to change — depends on another table. A subquery in WHERE handles the “which rows” part. Mark every order from customers in Lagos as priority by bumping its shipping fee:

SQL
UPDATE orders
SET shipping_fee = shipping_fee + 2.00
WHERE customer_id IN (SELECT id FROM customers WHERE city = 'Lagos')
  AND status = 'pending'
RETURNING id, customer_id, shipping_fee;
Text
 id | customer_id | shipping_fee 
----+-------------+--------------
 24 |           4 |        11.50
(1 row)

UPDATE 1

PostgreSQL’s UPDATE … FROM joins another table into the update, so you can also copy values across. Suppose the shop records each order’s total on the order itself. Add a column, then fill it from order_items:

SQL
ALTER TABLE orders ADD COLUMN items_total numeric(10,2);

UPDATE orders AS o
SET items_total = t.total
FROM (SELECT order_id, sum(quantity * unit_price) AS total
      FROM order_items
      GROUP BY order_id) AS t
WHERE t.order_id = o.id;

SELECT id, status, items_total FROM orders WHERE id <= 4 ORDER BY id;
Text
ALTER TABLE
UPDATE 24
 id |  status   | items_total 
----+-----------+-------------
  1 | delivered |       38.50
  2 | delivered |      113.00
  3 | delivered |       18.00
  4 | delivered |       62.25
(4 rows)

(ALTER TABLE … ADD COLUMN adds a column to an existing table — more in Changing table structure.) In UPDATE … FROM, the WHERE acts as the join condition. If it matches several rows of the other table for one target row, the result is unpredictable, so make sure it’s one-to-one — here, the subquery has exactly one row per order.

Other databases: SQL Server also has UPDATE … FROM; MySQL writes UPDATE orders o JOIN … SET …. Standard SQL uses a correlated subquery in SET, which works everywhere: SET items_total = (SELECT sum(…) FROM order_items WHERE order_id = orders.id).

DELETE

DELETE FROM removes the rows that match WHERE:

SQL
DELETE FROM products
WHERE name = 'Glass Teapot'
RETURNING id, name;
Text
 id |     name     
----+--------------
 11 | Glass Teapot
(1 row)

DELETE 1

The same rule applies, even more strongly: DELETE FROM products; with no WHERE deletes every product. Check with a SELECT first.

Deleting and foreign keys

Foreign keys protect relationships when you delete. Try deleting a customer who has orders:

SQL
DELETE FROM customers WHERE id = 2;
Text
ERROR:  update or delete on table "customers" violates foreign key constraint "orders_customer_id_fkey" on table "orders"
DETAIL:  Key (id)=(2) is still referenced from table "orders".

Refused: deleting Ben would leave four orders pointing at a customer who doesn’t exist. You’d have to delete (or reassign) his orders first. Customers without orders can be deleted freely:

SQL
DELETE FROM customers WHERE id = 10 RETURNING first_name;
Text
 first_name 
------------
 Jack
(1 row)

DELETE 1

A foreign key can be declared with a different behaviour. The Bean & Leaf order_items.order_id key says ON DELETE CASCADE: deleting an order automatically deletes its items:

SQL
SELECT count(*) AS items_before FROM order_items WHERE order_id = 5;
DELETE FROM orders WHERE id = 5;
SELECT count(*) AS items_after FROM order_items WHERE order_id = 5;
Text
 items_before 
--------------
            1
(1 row)

DELETE 1
 items_after 
-------------
           0
(1 row)

The options are NO ACTION/RESTRICT (refuse — the default), CASCADE (delete the children too) and SET NULL (keep the children but clear the reference). Cascades are convenient for things that can’t exist on their own, like order lines; they’re dangerous for important data, because one DELETE can quietly remove a lot.

Soft deletes

Many applications never physically delete important records. Instead they mark them — a deleted_at timestamp or is_active boolean column — and filter them out in queries. That keeps history, makes “undo” possible, and avoids fights with foreign keys. The cost is remembering WHERE deleted_at IS NULL everywhere (a view, covered in chapter 11, helps).

TRUNCATE: empty a table

To remove all rows from a table, TRUNCATE is much faster than DELETE — it doesn’t examine rows one by one, it just empties the table:

SQL
CREATE TABLE scratch_orders AS SELECT * FROM orders;   -- a copy to play with
TRUNCATE scratch_orders;
SELECT count(*) FROM scratch_orders;
Text
SELECT 23
TRUNCATE TABLE
 count 
-------
     0
(1 row)

It can’t have a WHERE, it refuses tables that other tables reference (unless you add CASCADE, which truncates those too), and TRUNCATE … RESTART IDENTITY also resets the id numbering. Use it for staging and scratch tables, rarely for real data.

Tip: many teams configure their SQL client to require confirmation for UPDATE or DELETE without WHERE, or open a transaction automatically. psql has no such switch, but \set AUTOCOMMIT off makes every change wait for an explicit COMMIT.

Exercise

A morning in the warehouse

Three changes. First, order 21 has been dispatched: set its status to 'shipped', returning id and status. Second, a delivery of 10 Burr Grinders (product 9) has arrived: add 10 to its stock, returning name and stock. Third, the owners want cancelled orders removed: delete every order with status 'cancelled', returning id (their items are removed automatically by the foreign key's ON DELETE CASCADE). Finish with a query that counts the remaining orders.

SQL
-- 1. Order 21 has shipped
UPDATE orders
SET ___
WHERE ___
RETURNING id, status;

-- 2. Ten more Burr Grinders in stock

-- 3. Remove cancelled orders, then count what's left

Summary

  • UPDATE table SET column = value WHERE condition changes the matching rows; SET can use the row's current values, as in stock = stock + 10.
  • Without WHERE, UPDATE and DELETE affect every row in the table — check the WHERE with a SELECT first.
  • UPDATE … FROM and subqueries let you change rows based on other tables.
  • Foreign keys protect related rows: deleting a parent is refused unless the key says ON DELETE CASCADE (or SET NULL).
  • TRUNCATE empties a whole table instantly; DELETE removes rows one by one and can be filtered.