A DELETE statement requires an exclusive lock on a table.If there are a significant number of deletes while simultaneously there is also a lot of SELECT traffic, this may impact performance. One trick that can be used is to turn the delete into an insert!
Consider the following example:
CREATE TABLE events
(eventid INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title CHAR(40));
Instead of deleting from the events table, interfering with all the selects, we do the following:
CREATE TABLE event_deletes (eventid INT UNSIGNED PRIMARY KEY);
To delete an event:
INSERT INTO event_deletes (329);
Now, to retrieve all non-deleted events:
SELECT e.eventid, e.title
FROM events e
LEFT JOIN event_deletes ed
ON e.eventid = ed.eventid
WHERE ed.eventid IS NULL;
or with a subquery :
SELECT e.eventid,e.title
FROM events e
WHERE NOT EXISTS
(SELECT * FROM event_deletes ed WHERE ed.eventid = e.eventid);
These SELECT statements merely use the index on the eventid column in the event_deletes table, no row data needs to be retrieved. During a maintenance timeslot, a script can go through the deleted items and delete the actual rows from the main table.
DELETE events
FROM events e,event_deletes ed
WHERE e.eventid = ed.eventid
DELETE FROM events_delete