Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leave only first 50 records in SQL database and delete the rest

I have a table of scores, which is made of 2 fields: name and high score. Something like this:

----------------------- 
| name     | score    |
-----------------------
| John     | 2450     |
-----------------------
| Alice    | 2420     |
-----------------------
                         ... etc    

I need to delete all the rows till the top 50 scores.

Is it possible without creating another temporary table ?

like image 876
Dusan Avatar asked Mar 20 '23 21:03

Dusan


2 Answers

please try this

delete from scores_tbl Where
id not in
(select * from
(select id from scores_tbl order by score desc limit 50)
 as temp)
like image 116
Yograj Sudewad Avatar answered Mar 23 '23 10:03

Yograj Sudewad


Create an auto increment field

alter table scores add id int unique auto_increment not null;

This will automatically number your rows in the order of a select query without conditions or order-by

select * scores;
delete from scores where id > 50;

Finally, remove that field

alter table scores drop id;
like image 24
Linga Avatar answered Mar 23 '23 09:03

Linga