← Back to Chapters

MySQL DELETE

?️ MySQL DELETE

? Quick Overview

The DELETE statement in MySQL is used to remove one or more records from a table. When working with PHP and MySQL, this command is commonly executed through database queries to permanently remove unwanted data.

? Key Concepts

  • DELETE removes rows permanently
  • WHERE controls which rows are removed
  • Without WHERE, all records are deleted
  • Commonly used with PHP database APIs like mysqli or PDO

? Syntax / Theory

? View Code Example
// Basic DELETE syntax in MySQL
DELETE FROM table_name WHERE condition;

? Example 1: Delete a Single Row

This query deletes the employee whose ID is 5 from the employees table.

? View Code Example
// Delete a specific employee by ID
DELETE FROM employees WHERE employee_id = 5;

? Example 2: Delete Multiple Rows

This query removes all employees earning less than 30000.

? View Code Example
// Delete employees with low salary
DELETE FROM employees WHERE salary < 30000;

⚠️ Delete All Rows

Omitting the WHERE clause deletes every record in the table while keeping the table structure intact.

? View Code Example
// Delete all records from employees table
DELETE FROM employees;

? PHP + MySQL DELETE Example

This example demonstrates executing a DELETE query using PHP and MySQLi.

? View Code Example
// PHP code to delete a record using MySQLi
$conn = mysqli_connect("localhost","root","","company");
$sql = "DELETE FROM employees WHERE employee_id = 5";
mysqli_query($conn,$sql);

? Live Output / Explanation

If the query executes successfully, the matching row is permanently removed from the database. No output is shown unless you manually display a success or error message in PHP.

? Interactive Concept

Think of DELETE as a filter + eraser. The WHERE clause selects rows, and MySQL erases only those rows. No undo is available unless a backup exists.

? Use Cases

  • Removing inactive users
  • Clearing expired sessions
  • Deleting obsolete records
  • Cleaning up test data

✅ Tips & Best Practices

  • Always test with SELECT before running DELETE
  • Use transactions when possible
  • Keep database backups
  • Prefer TRUNCATE for full-table cleanup

? Try It Yourself

  • Delete a product with zero stock
  • Remove users who are inactive for 1 year
  • Combine DELETE with LIMIT