• Top
  • Comment
  • Reply

Delete Query with Limit in Mysql

If you need to perform some clean up in your database one important think you come across, is how many live records in your database are optimal. So let say for our example we like to have 500 records in our live table at a time. However you cannot choose a date field as a deciding fact. Imagine if you deleted every thing in the last month, and more than 500 records came in last month. Then your live table will exceed the optimum number of rows.

Lets look at what we are trying to achieve.

DELETE * FROM table LIMIT 500;

To do this we first have to take a table structure in account

CREATE  TABLE IF NOT EXISTS `mytable` (
  `Id` BIGINT(20) NOT NULL,
  `dateReg` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id`)
)
ENGINE = InnoDB

Once we create the table we want to populate it.

INSERT INTO mytable(1, NULL);
INSERT INTO mytable(2, NULL);
....
INSERT INTO mytable(1000, NULL);

And then we use the delete query in such a way

DELETE FROM mytable WHERE Id NOT IN 
    (SELECT Id FROM mytable ORDER BY dateReg LIMIT 500);

Hope this helps

By

15th Jan 2011
© 2011 Shahmir Javaid - http://shahmirj.com/blog/10

Parixit Jani

2nd Dec 2013

Hi there recently I found the same requirement to delete record from table with limit
and I had use same code as you suggested in last delete query it shows this error:

"This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'"

so, To overcome from this I had use the same query with little change like :
DELETE FROM mytable WHERE Id NOT IN
(SELECT Id from (SELECT Id FROM mytable ORDER BY dateReg LIMIT 500) x);

and it was worked,

hope this help to needy worms.



Back to Top
All content is © copyrighted, unless stated otherwise.
Subscribe, @shahmirj, Shahmir Javaid+