Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL keep only the last X rows

I have a table in which the id is constantly increasing. The Id does not always increase by the same value and it is not an auto_increment due to a api, but it increases permanently. Example:

Id other content
501 xxx
500 yyy
365 qqq

Now I just want to keep the last X rows, remove rows with lower ids. I was able to find a similar but not a working solution for myself to this problem.

I thought that something like that would work, but there is an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

DELETE FROM `games` WHERE `matchId` NOT IN(SELECT `matchId` FROM `games` ORDER BY `matchId` DESC LIMIT X)

"#1235 – This version of MySQL doesn’t yet support ‘LIMIT & IN/ALL/ANY/SOME subquery’"

Im running the mysql version 8.0.27 on a phpmyadmin 5.1.1 web interface.

Is there a way to keep the newest x rows without triggering this error?

>Solution :

WITH cte AS (
 SELECT id, ROW_NUMBER() OVER (ORDER BY id DESC) AS rownum FROM games
)
DELETE games FROM games JOIN cte USING (id) WHERE rownum > 2;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading