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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With