Skip to content
Visual explainer 2h to learn 4 steps

INSERT, UPDATE, DELETE & RETURNING

Modify data safely and return the affected rows.

By Invicly Tech, , in SQL & PostgreSQL. About 9 minutes to read.

Topic 4 of 30

In short

INSERT, UPDATE and DELETE change data. The WHERE clause decides which rows are touched, so run risky changes inside a transaction and use RETURNING to see exactly which rows changed before committing.

Explained simply

So far you have only read data. DML (data manipulation language) is the set of commands that change it: INSERT adds new rows, UPDATE changes existing ones, and DELETE removes them. These are the commands behind every sign-up, edit and cancel button in an app.

All three are powerful, and two of them are dangerous. UPDATE and DELETE affect every row that matches the WHERE clause. Forget the WHERE and they affect every row in the table. There is no undo button unless you prepared one.

The prepared undo button is a transaction. Type BEGIN first, make your change, look at the result, and then choose COMMIT to keep it or ROLLBACK to throw it away. It is like writing in pencil before going over it in pen.

RETURNING is a Postgres bonus. It makes INSERT, UPDATE and DELETE give back the rows they touched, as if you had run a SELECT straight after. Apps use it to get the new id of a row they just created.

Press Play on a diagram to walk through it one step at a time.

FlowA safe data change
  1. 1
    BEGIN

    Start a transaction you can undo

  2. 2
    SELECT first

    Preview rows with the same WHERE

  3. 3
    UPDATE ... RETURNING

    Change rows and list what changed

  4. 4
    Check the result

    Row count and values as expected?

  5. 5
    COMMIT or ROLLBACK

    Keep the change, or undo it

SequenceTwo sessions during an uncommitted UPDATE
Session A
Postgres
Session B
  1. 1BEGIN; UPDATE price = 12 WHERE id = 7
    Session A to Postgres: BEGIN; UPDATE price = 12 WHERE id = 7
  2. 2SELECT price WHERE id = 7
    Session B to Postgres: SELECT price WHERE id = 7
  3. 3Still 10 (A not committed)
    Postgres to Session B: Still 10 (A not committed)
  4. 4COMMIT
    Session A to Postgres: COMMIT
  5. 5SELECT again
    Session B to Postgres: SELECT again
  6. 6Now 12
    Postgres to Session B: Now 12

In depth

INSERT in its different shapes

The basic shape lists the columns, then the values: INSERT INTO products (name, price) VALUES ('Pen', 1.5). Any column you leave out gets its DEFAULT, or NULL if it has none. Listing columns protects you when someone later adds or reorders columns.

You can insert many rows at once with several value lists separated by commas. That is far faster than one statement per row because it is one round trip and one commit.

You can also insert the result of a query: INSERT INTO archive_orders SELECT * FROM orders WHERE created_at < '2024-01-01'. The rows never leave the server, which makes this the quickest way to copy data between tables.

  • Always list column names
  • Multi-row VALUES: one trip, one commit
  • INSERT ... SELECT copies data inside the server
  • DEFAULT fills any column you skip

UPDATE using values from another table

Sometimes the new value lives in another table. Postgres lets you join during an update with UPDATE ... FROM. For example, to copy each customer's country onto their orders: UPDATE orders o SET country = c.country FROM customers c WHERE c.id = o.customer_id.

The WHERE clause does two jobs here: it joins the tables and it limits which rows change. If the join matches more than one row in the FROM table for the same target row, Postgres picks one of them unpredictably, so make sure the join is one-to-one.

Autocommit and why BEGIN matters

psql and most drivers start in autocommit mode: every statement is its own transaction and is committed the moment it succeeds. A mistaken DELETE is permanent before you can blink.

After BEGIN, nothing you change is visible to other sessions or permanent until COMMIT. If any statement fails, the whole transaction is marked as failed and Postgres refuses further statements until you ROLLBACK. That feels strict, but it stops half-finished changes from sneaking in.

Keep these manual transactions short. While open, they hold locks on the rows they changed, which can block other users.

CompareAutocommit vs an explicit transaction
Autocommit (default)
  • Each statement is its own transaction
  • Committed the moment it succeeds
  • A mistaken DELETE is permanent
BEGIN ... COMMIT
  • Changes hidden from others until COMMIT
  • ROLLBACK undoes everything
  • After an error, only ROLLBACK works
  • Holds row locks while open

DELETE vs TRUNCATE

DELETE FROM logs WHERE created_at < now() - interval '90 days' removes matching rows one by one. It can use a WHERE clause, fires triggers and supports RETURNING.

TRUNCATE logs empties the whole table instantly by throwing away its data files. It cannot filter, and it needs a stronger lock, but on a large table it takes milliseconds instead of minutes. Both can be rolled back inside a transaction in Postgres.

Deleting millions of rows in one DELETE creates a long transaction and lots of dead rows for VACUUM to clean. For big clean-ups, delete in batches of a few thousand rows.

CompareDELETE vs TRUNCATE
DELETE
  • Can filter with WHERE
  • Removes rows one by one
  • Fires row triggers, supports RETURNING
  • Leaves dead rows for VACUUM
TRUNCATE
  • Empties the whole table
  • Throws away data files: milliseconds
  • Needs a stronger lock
  • Can still be rolled back in Postgres

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Insert single and multiple rows~30m
  2. 2
    Update rows safely with WHERE~30m
  3. 3
    Delete rows inside a transaction~30m
  4. 4
    Return affected rows with RETURNING~30m

Key points

  • INSERT can add many rows in one statement with several VALUES lists.
  • UPDATE or DELETE without WHERE affects every row in the table.
  • RETURNING sends back the inserted, updated or deleted rows, including new ids.
  • psql commits each statement immediately unless you start with BEGIN.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
INSERT INTO products (name, price)
VALUES ('Pen', 1.50), ('Notebook', 4.00)
RETURNING id, name;

BEGIN;
UPDATE products
SET price = price * 1.10
WHERE category = 'stationery'
RETURNING id, name, price;
-- looks right? COMMIT; otherwise:
ROLLBACK;

DELETE FROM carts WHERE updated_at < now() - interval '90 days';

Creating an order and getting its id back

An app creates an order and must then add order lines that point to it. Step 1: INSERT the order with RETURNING id, so the database tells you the new id. Step 2: insert the lines using that id (shown here as 501). Step 3: wrap both in BEGIN and COMMIT so you never end up with an order that has no lines.

sql
BEGIN;
INSERT INTO orders (customer_id, status)
VALUES (17, 'new')
RETURNING id;          -- returns 501

INSERT INTO order_lines (order_id, product_id, qty)
VALUES (501, 3, 2), (501, 9, 1);
COMMIT;

Fixing bad data without fear

Some emails were saved with capital letters and spaces. Step 1: preview the rows with SELECT and the same WHERE. Step 2: BEGIN. Step 3: UPDATE with RETURNING to see old and new. Step 4: check the reported row count matches the preview (say UPDATE 37). Step 5: COMMIT. If the count had been 37,000, you would ROLLBACK and look for the bug in the WHERE.

sql
SELECT id, email FROM users WHERE email <> lower(trim(email));

BEGIN;
UPDATE users
SET email = lower(trim(email))
WHERE email <> lower(trim(email))
RETURNING id, email;
-- UPDATE 37, as expected
COMMIT;

Quick reference

  • INSERT INTO t (a, b) VALUES (1, 'x'), (2, 'y') RETURNING id;
  • UPDATE t SET a = a + 1 WHERE id = 5 RETURNING *;
  • UPDATE t SET col = s.col FROM s WHERE s.id = t.s_id; (update from another table)
  • DELETE FROM t WHERE cond RETURNING *;
  • Run SELECT with the same WHERE before any UPDATE or DELETE
  • BEGIN ... COMMIT or ROLLBACK; psql otherwise autocommits each statement
  • TRUNCATE t empties a whole table fast; DELETE can filter
  • Delete millions of rows in batches, not one giant statement

Common mistakes

  • Running UPDATE without WHERE and changing every row.
  • Forgetting that autocommit made a mistake permanent instantly.
  • Inserting without listing column names, which breaks when columns change.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does UPDATE products SET price = 0; do?

Question 2

2Why use INSERT ... RETURNING id?

Question 3

3Inside BEGIN, one statement fails. What happens to later statements?

Question 4

4Which is the best way to empty a 50-million-row staging table completely?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Insert three products (name, price) in one statement and return their ids and names.

  2. Exercise 2medium

    Inside a transaction, raise the price of every product in category 'toys' by 5%, rounded to 2 decimals, show the changed rows, then undo it.

  3. Exercise 3hard

    Move all orders older than 2023 from orders into orders_archive in a single statement, so a row can never be lost or copied twice.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can I undo a DELETE after it is committed?
Not with SQL. You would have to restore from a backup, which is why risky changes belong inside BEGIN and ROLLBACK until you have checked them.
What does "UPDATE 0" mean?
The statement ran fine but no rows matched the WHERE clause. Check your condition with a SELECT.
Is RETURNING standard SQL?
It is a PostgreSQL extension, also supported by SQLite and MariaDB in some forms. Other databases offer similar features like OUTPUT in SQL Server.

Go deeper

ShareXLinkedInWhatsApp