Browse topics

UPDATE and DELETE

Version
19
Review
Draft

Summary#

UPDATE changes rows and DELETE removes them. Both can consult other tables, with FROM for updates and USING for deletes, and report affected rows with RETURNING.

Syntax#

sql
UPDATE target AS t
SET column_name = s.column_name
FROM source AS s
WHERE t.key_column = s.key_column
RETURNING old.column_name, new.column_name;

DELETE FROM target AS t
USING source AS s
WHERE t.key_column = s.key_column
RETURNING t.key_column;

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.

sql
BEGIN;

CREATE TEMPORARY TABLE products (
    product_id integer PRIMARY KEY,
    name       text NOT NULL,
    category   text NOT NULL,
    price      numeric(8,2) NOT NULL
);

CREATE TEMPORARY TABLE adjustments (
    category text PRIMARY KEY,
    factor   numeric(4,2) NOT NULL
);

CREATE TEMPORARY TABLE retired (product_id integer PRIMARY KEY);

INSERT INTO products VALUES
    (1, 'lamp', 'home', 40.00), (2, 'desk', 'office', 150.00),
    (3, 'chair', 'office', 90.00), (4, 'rug', 'home', 60.00);
INSERT INTO adjustments VALUES ('office', 1.10);
INSERT INTO retired VALUES (4);

-- UPDATE joined to another table.
WITH repriced AS (
    UPDATE products AS p
    SET price = round(p.price * a.factor, 2)
    FROM adjustments AS a
    WHERE p.category = a.category
    RETURNING p.product_id, p.name, old.price AS was, new.price AS now
)
SELECT name, was, now FROM repriced ORDER BY product_id;

-- DELETE joined to another table.
DELETE FROM products AS p
USING retired AS r
WHERE p.product_id = r.product_id
RETURNING p.product_id, p.name;

SELECT product_id, name, price FROM products ORDER BY product_id;

ROLLBACK;

Expected output#

Text
name|was|now
desk|150.00|165.00
chair|90.00|99.00
(2 rows)
product_id|name
4|rug
(1 row)
product_id|name|price
1|lamp|40.00
2|desk|165.00
3|chair|99.00
(3 rows)

Common mistakes#

If FROM matches one target row with several source rows, only one of them is used and you cannot reliably predict which. Make the source unique on the join key. Omitting the join condition or the whole WHERE clause affects far more rows than intended.

Version applicability#

The old and new names in RETURNING require PostgreSQL 18. On earlier versions, an update returns new values and a delete returns the deleted values through ordinary column references. The first statement also uses a data-changing CTE, available since 9.1.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0