I was wondering if there is a way to delete everything but the first 100 rows in a a table in a mysql database. Can this be done using the phpmyadmin GUI.
-
@FastSnail So you can select 100 you want to KEEP and delete the rest ? – seus Jul 15 '16 at 02:40
-
1something like: `delete from foo where id >100` – Jul 15 '16 at 02:40
-
1@seus sorry i misread it.i think it's hard to do in gui.but you can edit mysql query in the gui .check this question http://stackoverflow.com/questions/17292375/delete-all-rows-except-first-n-from-a-table-having-single-column – Madhawa Priyashantha Jul 15 '16 at 02:46
-
@Dragon how do i cascade deletes with all foreign keys? – seus Jul 15 '16 at 02:50
3 Answers
Yes, it is possible, depending what you mean by "first 100". I'm assuming you have an auto-increment primary key column (e.g. id
) and the "first 100" rows would be the rows that show up first when ordered by that column. If so, to find the last id
of the first 100 rows, you'd write:
SELECT MAX(m.id) FROM (SELECT id FROM mytable ORDER BY id LIMIT 100) m
Now, you want to delete any rows with the id
greater than this max, so you write:
DELETE FROM
mytable
WHERE
id > (SELECT MAX(m.id)
FROM
(SELECT id FROM mytable ORDER BY id LIMIT 100) m);
Here's the sqlfiddle that's demonstrating this for 5 rows.

- 1,151
- 7
- 14
-
-
You also can do: `DELETE FROM mytable WHERE id IN (SELECT id FROM mytable ORDER BY id LIMIT 100);` – Rodrigo Chaves Nov 16 '21 at 21:11
Can I suggest you alternative approach. Let me know if it works for you?
CREATE TABLE newtable LIKE oldtable;
INSERT newtable SELECT * FROM oldtable LIMIT 100;
It will a create new table with first 100 records, this way you will keep backup of old table also. if you want it then keep it or delete it.

- 1,145
- 1
- 8
- 17
-
LIMIT without ORDER BY is fairly meaningless. Also, this needn't be two separate queries. Basically, this is a good approach, but it needs some tweaking. – Strawberry Jul 15 '16 at 07:09
-
I think I've made it clear, It is an alternative approach which can solve the question. If required you can always add ORDER BY clause. – Shrikant Mavlankar Jul 15 '16 at 07:17
-
try this:
Delete from table where id > 0 and id <101
this will delete the record from 1 to 100 unless you create a loop of it..
loop will do in stored proc i guess..

- 4,153
- 1
- 16
- 30