2

I have a table with unknow number of rows in it. I need to remove all the rows, except a fixed number of records.

Example: Table 1 has 439 rows. I need to keep 200 rows randomly and delete others.

The "logic way" is:

DELETE FROM table_1 
WHERE id NOT IN (SELECT id FROM table_1 ORDER BY RAND() LIMIT 200)``` 

But mariaDB says

You cannot use LIMIT in subquery ...

How I can do it? Thanks in advance!

lemon
  • 14,875
  • 6
  • 18
  • 38
Matt Ross
  • 67
  • 7

1 Answers1

3

Here's a solution tested on MariaDB 10.6:

delete t1 from table_1 as t1
left join (select id from table_1 order by rand() limit 200) as t2
using (id)
where t2.id is null;

Demo: https://dbfiddle.uk/zygpZ0u0

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828