Beginner · Databases and SQL basics · topic 19 of 54 · 25 min
INSERT, UPDATE and DELETE
Explanation
Adding rows with INSERT
INSERT INTO is followed by the table name, the list of columns, and VALUES with the data in the same order. Naming the columns is safer than relying on the table's column order, because tables change over time.
INSERT INTO orders (id, customer, city, amount, status)
VALUES (7, 'Meena', 'Jaipur', 999, 'Placed');
-- many rows in one statement
INSERT INTO orders (id, customer, city, amount, status)
VALUES (8, 'Sunil', 'Indore', 450, 'Placed'),
(9, 'Fatima', 'Lucknow', 1299, 'Placed');Changing rows with UPDATE
UPDATE table SET column = new value WHERE condition. SET can change several columns, separated by commas, and the new value can use the old one, like amount = amount + 50.
UPDATE orders
SET status = 'Shipped'
WHERE id = 3;Removing rows with DELETE
DELETE FROM orders
WHERE status = 'Cancelled';The danger of forgetting WHERE
Seeing what changed: RETURNING
PostgreSQL and SQLite (since version 3.35) support RETURNING at the end of INSERT, UPDATE or DELETE. It gives back the changed rows, which is handy in an API: INSERT ... RETURNING id tells you the id of the new row. In the tasks below we use a separate SELECT after the change instead, so you can see the whole table.
INSERT INTO orders (customer, city, amount, status)
VALUES ('Ritu', 'Bhopal', 640, 'Placed')
RETURNING id;Watch the lesson
INSERT, UPDATE and DELETE · 1/6
Reading data is half the job. Today we add, change and remove rows.
Prefer a video by a teacher? Find free videos on “sql insert update delete tutorial for beginners” on YouTube ↗
In real life: An order's life in a food delivery app
When you place an order, the backend runs an INSERT to add a row with status Placed. When the restaurant accepts it, an UPDATE sets status = 'Preparing' WHERE id = your order id; later another UPDATE sets it to 'Out for delivery' and then 'Delivered'. Many apps do not really DELETE old orders; they keep them for bills and tax records and only mark them cancelled. Real deletes are kept for things like removing a user's data when they close their account.
Practice (0/3 done)
Add a new order to the orders table (columns id, customer, city, amount, status): id 7, customer Meena, city Jaipur, amount 999, status Placed. The SELECT at the end is already written: it shows the new row so the checker can see it. Write your INSERT above it.
Priya's order (id 3) has left the warehouse. Change its status to Shipped. Change ONLY that order. The SELECT at the end is already written: it shows every order's status after your change.
Remove every order whose status is Cancelled, and nothing else. The SELECT at the end is already written: it lists the orders that are left.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.