← Back to Chapters

MySQL DELETE

?️ MySQL DELETE

Quick Overview

The DELETE statement is used to remove existing records from a table in MySQL based on a given condition. Use it with caution — without a WHERE clause all rows will be removed.

Key Concepts

  • DELETE — command to remove rows from a table.
  • FROM — specifies which table to delete from.
  • WHERE — filters which rows should be deleted; essential to avoid full-table deletion.
  • TRUNCATE — faster alternative to remove all rows but not transactional.

Syntax / Theory

? View Code Example
-- Syntax for DELETE (preview before running)
DELETE FROM table_name WHERE condition;

Code Example(s)

? View Code Example
-- Delete a record from the 'students' table where the name is 'John Doe' (comment)
DELETE FROM students WHERE name = 'John Doe';
? View Code Example
-- Delete multiple records where the age is less than 18 (comment)
DELETE FROM students WHERE age < 18;

Live Output / Explanation

What happens when you run DELETE

Matching rows are removed immediately. If you need the ability to undo, perform deletes inside a transaction (if your storage engine supports it) so you can ROLLBACK if necessary. Always preview with SELECT first.

Example preview command:

? View Code Example
-- Preview rows that would be deleted to verify before deleting (comment)
SELECT * FROM students WHERE age < 18;

✅ Tips & Best Practices

  • Run a SELECT with the same WHERE clause before deleting to preview affected rows.
  • Wrap large deletes in transactions when possible so you can rollback if needed.
  • Use TRUNCATE to clear an entire table for performance, but note it's not transactional.
  • Back up important data before performing bulk deletions.

? Try It Yourself / Practice Tasks

  • Write a query to delete a student record with a specific id.
  • Delete all students from a specific city and preview with a SELECT first.
  • Practice wrapping a delete in a transaction (BEGIN; DELETE ...; ROLLBACK;) to observe rollback behavior.