Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DELETE with a percentage on total count

Tags:

sql

mysql

Let's say I want to delete 10% of rows, is there a query to do this?

Something like:

DELETE FROM tbl WHERE conditions LIMIT (SELECT COUNT(*) FROM tbl WHERE conditions) * 0.1
like image 722
dynamic Avatar asked Apr 28 '12 11:04

dynamic


People also ask

How do I count a percentage in SQL?

There is no built-in operator that calculates percentages in SQL Server. You have to rely on basic arithmetic operations i.e. (number1/number2 x 100) to find percentages in SQL Server.

How do I DELETE a specific number of rows in SQL?

If you wanted to delete a number of rows within a range, you can use the AND operator with the BETWEEN operator. DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; Another way to delete multiple rows is to use the IN operator.


2 Answers

If you only need roughly 10% of rows, in no particular order, this should do the trick:

DELETE FROM tbl WHERE RAND() <= 0.1

However, I don't recommend using it on very large data sets due to the overhead of generating random numbers.

like image 60
Polynomial Avatar answered Oct 12 '22 19:10

Polynomial


I would simply return the total amount of filtered rows, calculate through php and use that value as a limit in my DELETE query.

$query = mysql_query("SELECT COUNT(*) FROM tbl WHERE conditions");
$int = reset(mysql_fetch_array($query));
$int = round($int * 0.1);

mysql_query("DELETE FROM tbl WHERE conditions LIMIT {$int}");

I'm not sure if DELETE allows an advanced query such as this one:

DELETE FROM (   SELECT h2.id
                FROM (  SELECT COUNT(*) AS total
                        FROM tbl
                        WHERE conditions) AS h
                JOIN (  SELECT *, @rownum := @rownum + 1 AS rownum
                        FROM tbl, (SELECT @rownum := 0) AS vars
                        WHERE conditions) AS h2
                ON '1'
                WHERE rownum < total * 0.1) AS h3
like image 28
Robin Castlin Avatar answered Oct 12 '22 19:10

Robin Castlin