← SQL roadmap

Topic 17 of 52 · Beginner

INSERT, UPDATE, DELETE

Add, change and remove rows safely.

Concept

INSERT adds rows; you can insert many rows in one statement or insert from a SELECT.

UPDATE changes existing rows and DELETE removes them. Always write the WHERE clause first — without it, every row is affected.

MySQL supports upserts with INSERT ... ON DUPLICATE KEY UPDATE, which updates the row if the key already exists.

Code (SQL · MySQL 8)

INSERT INTO customers (name, email, city) VALUES
  ('Asha', 'asha@mail.com', 'Hyderabad'),
  ('Ravi', 'ravi@mail.com', 'Chennai');

UPDATE customers SET city = 'Bengaluru' WHERE id = 2;

DELETE FROM customers WHERE created_at < '2020-01-01';

-- Upsert
INSERT INTO customers (id, name, email) VALUES (1, 'Asha K', 'asha@mail.com')
ON DUPLICATE KEY UPDATE name = VALUES(name);

Remember

  • No WHERE = every row changes.
  • Run the WHERE as a SELECT first to preview affected rows.
  • INSERT ... SELECT copies data between tables.

Interview questions

How do you insert only if the row doesn't exist?

Use INSERT IGNORE, or INSERT ... ON DUPLICATE KEY UPDATE, or INSERT ... SELECT ... WHERE NOT EXISTS (...).

How do you safely run a big UPDATE?

Preview with SELECT, wrap in a transaction, update in batches with LIMIT, and verify the row count before COMMIT.

Practise SQL with the AI mentor

Lesson test

Take an 8-question test on “INSERT, UPDATE, DELETE” — concepts, output prediction, bug spotting and interview questions.

Can't find a SQL topic you need for exams or placements? Request it and we'll add it.