Skip to the content

Lesson 214 of 296

INSERT, UPDATE, DELETE and upsert

What you will learn

  • Adding rows with INSERT
  • Changing rows with UPDATE
  • Removing rows with DELETE
  • RETURNING
  • Upsert with ON CONFLICT
  • TRUNCATE vs DELETE vs DROP
  • Parameterised queries
On this page

INSERT

SQL
INSERT INTO products (id, name, category, price_pence)
VALUES (6, 'Water Bottle', 'Kitchen', 1599)
RETURNING id, name;
idname
6Water Bottle
  • Always list the columns: the statement keeps working if columns are added or reordered.
  • Insert several rows at once: VALUES (...), (...), (...): much faster than one statement per row.
  • RETURNING (PostgreSQL) gives back the inserted row, including generated values like IDs and defaults, without a second query.
  • Usually IDs are generated by the database: id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY (older code uses serial), or uuid DEFAULT gen_random_uuid().

UPDATE

SQL
UPDATE products SET price_pence = 949 WHERE id = 1 RETURNING name, price_pence;
nameprice_pence
Mug949

Always include a WHERE clause. UPDATE products SET price_pence = 949; changes every product. A good habit: write and run the WHERE as a SELECT first to see which rows will change, and do risky changes inside a transaction (Lesson 223) so you can roll back.

Update using another table (PostgreSQL syntax):

SQL
UPDATE orders o SET status = 'cancelled'
FROM customers c
WHERE c.id = o.customer_id AND c.email = 'dara@example.com' AND o.status = 'pending'
RETURNING o.id, o.status;
idstatus
105cancelled

DELETE

SQL
DELETE FROM products WHERE id = 6 RETURNING name;
name
Water Bottle

Deleting a row that other rows reference fails because of the foreign key:

SQL
DELETE FROM customers WHERE id = 1;

Result: ERROR: update or delete on table "customers" violates foreign key constraint "orders_customer_id_fkey" on table "orders". This protects you from orphaned orders. Options are covered in Lesson 226 (ON DELETE CASCADE and others) and soft deletes in Lesson 228.

Upsert: insert or update

"Insert this row; if it already exists, update it instead": an upsert. In PostgreSQL:

SQL
INSERT INTO products (id, name, category, price_pence)
VALUES (2, 'Notebook', 'Stationery', 500)
ON CONFLICT (id) DO UPDATE SET price_pence = EXCLUDED.price_pence
RETURNING id, name, price_pence;
idnameprice_pence
2Notebook500
  • ON CONFLICT (column) needs a unique constraint or primary key on that column.
  • EXCLUDED refers to the row you tried to insert.
  • ON CONFLICT DO NOTHING simply skips duplicates: useful for idempotent processing (Lesson 195).
  • An upsert is atomic: safe even when two requests run at once, unlike "SELECT, then INSERT or UPDATE" in application code, which has a race condition.
  • MySQL uses INSERT ... ON DUPLICATE KEY UPDATE; the SQL standard (and PostgreSQL 15+) also has MERGE.

TRUNCATE vs DELETE vs DROP

CommandEffect
DELETE FROM t WHERE ...Removes chosen rows; can be filtered; fires triggers
TRUNCATE tRemoves all rows very quickly; cannot be filtered
DROP TABLE tRemoves the whole table, structure and data

Parameterised queries

In application code, never build SQL by joining strings with user input:

db.query("SELECT * FROM customers WHERE email = '" + email + "'")       SQL injection (Lesson 260)
db.query("SELECT * FROM customers WHERE email = $1", [email])           correct

With parameters ($1, $2), the database receives the values separately from the SQL text, so input can never change the meaning of the query. Query builders and ORMs (Prisma, Lesson 230) do this for you.

How to say it in an interview

"INSERT adds rows, always listing the columns and inserting in batches; UPDATE and DELETE always need a WHERE clause, which I check with a SELECT first and run inside a transaction when risky. PostgreSQL's RETURNING gives back changed rows without another query. Upsert with INSERT ON CONFLICT DO UPDATE, using EXCLUDED for the new values, is atomic and needs a unique constraint, unlike select-then-insert, which races. TRUNCATE empties a table fast and DROP removes it. In code I always use parameterised queries to prevent SQL injection."

Key words

WordMeaning
INSERT / UPDATE / DELETEAdd / change / remove rows
RETURNINGReturn the affected rows (PostgreSQL)
UpsertInsert, or update if the row exists
ON CONFLICTPostgreSQL's upsert clause
EXCLUDEDThe row that was proposed for insertion
Parameterised querySQL with placeholders and separate values

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.