MySQL Delete Data

Ma Mahalakshmi V Updated 14 Nov 2026
5 min read ·Lesson 203 of 256

Removing Rows From a Table

In simple terms: DELETE removes rows from a table — a cancelled draft, a test account, an expired login token. Deleting is permanent: once the statement runs (and the transaction is committed), the data is gone. That is why deletes must always be targeted precisely and handled with care.

Technically: DELETE FROM table WHERE condition removes every row that matches the condition. Without a WHERE clause, it removes all rows. After execution, affected_rows reports how many rows were deleted. Foreign key constraints may block a delete (ON DELETE RESTRICT) or automatically delete related rows (ON DELETE CASCADE).


Syntax

DELETE FROM customers
WHERE id = ?;

Warning: DELETE FROM customers; — without WHERE — deletes every customer. Always write the WHERE clause first, and test the condition with a SELECT before running a delete on important data.


Deleting a Row With a Prepared Statement

<?php
require __DIR__ . '/src/db.php';

function deleteCustomerByEmail(mysqli $db, string $email): string
{
    $db->execute_query('DELETE FROM customers WHERE email = ?', [$email]);

    return $db->affected_rows === 1
        ? "Deleted customer $email"
        : "No customer found with $email";
}

echo deleteCustomerByEmail(db(), 'test@example.com') . "\n";
echo deleteCustomerByEmail(db(), 'test@example.com') . "\n";

Output

Deleted customer test@example.com
No customer found with test@example.com

How It Works

  1. The email is passed as a parameter; the WHERE clause matches exactly one row thanks to the UNIQUE index on email.
  2. affected_rows is 1 after the first call and 0 after the second — deleting a non-existent row is not an error, so check affected_rows to know whether anything happened.
  3. The function reports the outcome so the calling code (or user) gets meaningful feedback.

The order_items.product_id foreign key uses ON DELETE RESTRICT (see MySQL Create Table). Deleting a product that appears in an order is therefore rejected:

<?php
require __DIR__ . '/src/db.php';

try {
    db()->execute_query('DELETE FROM products WHERE sku = ?', ['PEN-01']);
} catch (mysqli_sql_exception $e) {
    echo "Error {$e->getCode()}\n";
    echo $e->getMessage() . "\n";
}

Output

Error 1451
Cannot delete or update a parent row: a foreign key constraint fails (`gocourse_shop`.`order_items`, CONSTRAINT `fk_items_product` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE RESTRICT)

The Gel Pen is part of order #501, and deleting it would leave that order referring to a product that no longer exists. MySQL refuses. In the application, translate error 1451 into a helpful message, such as "This product has been ordered and cannot be deleted. Deactivate it instead."

Cascading Deletes

The order_items.order_id foreign key uses ON DELETE CASCADE, so deleting an order automatically deletes its items:

<?php
require __DIR__ . '/src/db.php';

$db = db();

// A temporary test order with one item
$db->query('INSERT INTO orders (id, customer_id, status, total) VALUES (900, 2, "pending", 60.00)');
$db->query('INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (900, 2, 1, 60.00)');

$countItems = fn(): int => (int) $db->query('SELECT COUNT(*) FROM order_items WHERE order_id = 900')->fetch_column();

echo "Items before: " . $countItems() . "\n";

$db->execute_query('DELETE FROM orders WHERE id = ?', [900]);
echo "Orders deleted: {$db->affected_rows}\n";
echo "Items after: " . $countItems() . "\n";

Output

Items before: 1
Orders deleted: 1
Items after: 0

affected_rows counts only rows deleted directly from orders; the cascaded item rows are removed automatically. Cascades are convenient for data that has no meaning without its parent (order items without an order). For important records (customers, products), RESTRICT is safer.


Soft Deletes: Hiding Instead of Removing

Many applications never physically delete important records. Instead, they mark them as deleted:

ALTER TABLE customers ADD COLUMN deleted_at DATETIME NULL;
<?php
function softDeleteCustomer(mysqli $db, int $id): bool
{
    $db->execute_query('UPDATE customers SET deleted_at = NOW() WHERE id = ? AND deleted_at IS NULL', [$id]);
    return $db->affected_rows === 1;
}

// Every normal query must then exclude deleted rows:
// SELECT ... FROM customers WHERE deleted_at IS NULL

Hard Delete vs Soft Delete

Hard Delete (DELETE)Soft Delete (deleted_at)
Data recoverableNo (only from backups)Yes
Related records stay validMust be handled by foreign keysYes, references remain
QueriesSimpleMust filter deleted_at IS NULL everywhere
Privacy (right to erasure)Data is goneData still exists; may need real deletion or anonymization
Unique constraintsFreed immediatelyThe email remains "taken" unless handled

ORMs such as Laravel's Eloquent apply the deleted_at IS NULL filter automatically. For personal data, data protection laws may require real deletion or anonymization after a request — soft deletes alone are not enough.


Deleting Many Rows

Deleting by Condition

<?php
// Remove expired password-reset tokens (example table)
$db->execute_query('DELETE FROM password_resets WHERE expires_at < ?', [gmdate('Y-m-d H:i:s')]);
echo "Removed {$db->affected_rows} expired tokens\n";

Deleting in Batches

Deleting millions of rows in one statement can lock the table for a long time and fill the transaction log. Delete in chunks instead:

<?php
do {
    $db->execute_query('DELETE FROM activity_log WHERE created_at < ? LIMIT 1000', ['2025-01-01']);
} while ($db->affected_rows === 1000);

TRUNCATE

TRUNCATE TABLE logs; removes all rows very quickly and resets the AUTO_INCREMENT counter. It cannot be rolled back, does not run row-level checks, and fails on tables referenced by foreign keys. Use it only for staging or log tables.


Deleting Safely From a Web Interface

  • Use POST (or DELETE) requests, never GET links: browsers, prefetchers, and crawlers follow links automatically.
  • Protect with CSRF tokens (see CSRF Protection).
  • Check authorization: a user may delete only records they own or are allowed to manage — DELETE FROM orders WHERE id = ? AND customer_id = ?.
  • Ask for confirmation before destructive actions, and consider an "undo" period (soft delete first, purge later).
  • Keep backups: regular, tested database backups are the final safety net.

Common Mistakes

Forgetting the WHERE Clause

Effect: All rows are deleted.

Fix: Write and test the WHERE condition first; consider enabling MySQL's sql_safe_updates option in interactive sessions.

Effect: Data is deleted by crawlers or prefetching.

Fix: Use POST forms with CSRF tokens.

Ignoring affected_rows

Effect: The application reports success although nothing was deleted.

Fix: Check affected_rows.

Not Handling Foreign Key Errors

Effect: Users see raw database errors.

Fix: Catch error 1451 and show a helpful message, or deactivate records instead.


Best Practices

  • Always delete with a precise WHERE clause and prepared statement parameters.
  • Check affected_rows to confirm the result.
  • Choose RESTRICT or CASCADE deliberately for each relationship.
  • Prefer soft deletes or deactivation for important business records.
  • Delete large amounts of data in batches, and keep reliable backups.

Official reference: https://www.php.net/manual/en/mysqli.query.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about MySQL Delete Data and get answers drawn from it.

Signed-in readers only.