6

I have a table with an unknown number of records. I want to delete half of the records. I don’t care which records are deleted. What’s the most efficient way to do it?

1
  • This answer would be greatly improved with an example of why you want to do this, perhaps what you want to accomplish. For instance, do you want to save drive space? Improve lookup times? Is this a personal file on your local machine, or a production database? etc.
    – Ky -
    Jul 8, 2020 at 16:33

1 Answer 1

28
delete from some_table where rand() < 0.5;

This will delete about half the records, most of the time.

6
  • rand() wont necessairly give you 50% though, especially for smaller datasets. If you're allowed to use two queries, I'd say count the number of rows with the first one and then use a LIMIT on your delete query... but I feel like there might be a way to do it with a single query, however you cannot have subqueries on the LIMIT. So it must have something to do with the table's structure... but that's not given with the question.... hmmmmm SELECT COUNT(*) FROM table; then DELETE FROM table LIMIT rows/2; Jan 17, 2012 at 7:28
  • @Greg Hewgill: perfect answer, +1
    – zerkms
    Jan 17, 2012 at 7:32
  • @Authman Apatira: even with 2 queries and COUNT(*) you couldn't delete exact a half rows when for example there is 7 rows total.
    – zerkms
    Jan 17, 2012 at 7:36
  • 7
    I think this is the best solution (in the case you have a auto_incremented primary key) DELETE FROM tabletodelete WHERE id % 2 = 0 Apr 19, 2015 at 15:56
  • 1
    @FabriceKabongo I suggest you to create an answer to the question. The solution is really elegant!
    – rilaby
    May 4, 2016 at 13:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.