Bulk Delete with a Simple Condition

This section provides a tutorial example on bulk deletion with a simple condition on a large table.

You can run the DELETE statement directly for a bulk deletion with a simple condition on a large table.

For example, deleting all order lines of a given product category from a large sales order database, you can use this DELETE statement to get the job done by following suggested steps below.

DELETE from OrderLines where ProductCategory = 'DAIRY';

1. Preparation on the MySQL server:

2. Drop indexes that is not needed by the DELETE statement like ProductID. This will avoid the effort maintaining those indexes during the execution of the DELETE statement. Of course, you need to re-create those indexes after the execution.

DROP INDEX ProductID on OrderLines;

3. Run some count statements. I see that we are about to delete 30% of 5,535,548 rows.

mysql> select count(*) as total from OrderLines
  | total   |
  +---------+
  | 5535548 |

mysql> select count(*) as target from OrderLines
    -> where ProductCategory = 'DAIRY';
  | target  |
  +---------+
  | 1664652 |

mysql> select 1664652/5535548 as percent;
  | percent |
  +---------+
  |  0.3007 |

4. Run the DELETE statement. The performance is not too bad.

mysql> delete from from OrderLines where ProductCategory = 'DAIRY';
Query OK, 1664652 rows affected (3 min 55.39 sec)

5. Post-change actions:

Table of Contents

 About This Book

 Introduction of SQL

 MySQL Introduction and Installation

 Introduction of MySQL Programs

 PHP Programs and MySQL Server

 Perl Programs and MySQL Servers

 Java Programs and MySQL Servers

 Datatypes and Data Literals

 Operations and Expressions

 Character Strings and Bit Strings

 Commonly Used Functions

 Table Column Types for Different Types of Values

 Using DDL to Create Tables and Indexes

 Using DML to Insert, Update and Delete Records

 Using SELECT to Query Database

 Window Functions for Statistical Analysis

 Use Index for Better Performance

 Transaction Management and Isolation Levels

 Locks Used in MySQL

 Defining and Calling Stored Procedures

 Variables, Loops and Cursors Used in Stored Procedures

 System, User-Defined and Stored Procedure Variables

 MySQL Server Administration

 Storage Engines in MySQL Server

 InnoDB Storage Engine - Primary and Secondary Indexes

 Performance Tuning and Optimization

Bulk Changes on Large Tables

 General Guidelines on Bulk Changes

Bulk Delete with a Simple Condition

 Delete Records That Are Not Referenced

 Reset AUTO_INCREMENT Value on Large Tables

 MySQL Server on macOS

 Installing MySQL Server on Linux

 Connection, Performance and Second Instance on Linux

 Archived Tutorials

 References

 Full Version in PDF/EPUB