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
INSERT INTO products (id, name, category, price_pence)
VALUES (6, 'Water Bottle', 'Kitchen', 1599)
RETURNING id, name;| id | name |
|---|---|
| 6 | Water 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 usesserial), oruuid DEFAULT gen_random_uuid().
UPDATE
UPDATE products SET price_pence = 949 WHERE id = 1 RETURNING name, price_pence;| name | price_pence |
|---|---|
| Mug | 949 |
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):
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;| id | status |
|---|---|
| 105 | cancelled |
DELETE
DELETE FROM products WHERE id = 6 RETURNING name;| name |
|---|
| Water Bottle |
Deleting a row that other rows reference fails because of the foreign key:
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:
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;| id | name | price_pence |
|---|---|---|
| 2 | Notebook | 500 |
ON CONFLICT (column)needs a unique constraint or primary key on that column.EXCLUDEDrefers to the row you tried to insert.ON CONFLICT DO NOTHINGsimply 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 hasMERGE.
TRUNCATE vs DELETE vs DROP
| Command | Effect |
|---|---|
DELETE FROM t WHERE ... | Removes chosen rows; can be filtered; fires triggers |
TRUNCATE t | Removes all rows very quickly; cannot be filtered |
DROP TABLE t | Removes 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]) correctWith 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
| Word | Meaning |
|---|---|
| INSERT / UPDATE / DELETE | Add / change / remove rows |
| RETURNING | Return the affected rows (PostgreSQL) |
| Upsert | Insert, or update if the row exists |
| ON CONFLICT | PostgreSQL's upsert clause |
| EXCLUDED | The row that was proposed for insertion |
| Parameterised query | SQL with placeholders and separate values |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.