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?
-
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
Add a comment
|
1 Answer
delete from some_table where rand() < 0.5;
This will delete about half the records, most of the time.
-
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
-
-
@Authman Apatira: even with 2 queries and
COUNT(*)
you couldn't delete exact a half rows when for example there is 7 rows total.– zerkmsJan 17, 2012 at 7:36 -
7I 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!– rilabyMay 4, 2016 at 13:58