Last active
November 8, 2021 14:55
-
-
Save porsager/59169eaa91e2bf1be0267558ea9dc780 to your computer and use it in GitHub Desktop.
Remove all but the latest n rows with group by
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Simply set the offset to the amount of rows you want to keep. An index of (id, date desc) will make this fast. | |
delete from some_table st | |
using ( | |
select distinct | |
x.id, | |
x.date | |
from some_table st1 | |
join lateral ( | |
select | |
id, date | |
from some_table st2 | |
where st2.id = st1.id | |
order by st2.date desc | |
limit 1 | |
offset 1000 | |
) x on true | |
) x2 | |
where st.id = x2.id and st.date <= x2.date |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
delete from some_table st | |
using ( | |
select | |
id, | |
date | |
from ( | |
select | |
id, | |
date, | |
row_number() over ( | |
partition by id | |
order by date desc | |
) | |
from some_table | |
) where row_number > 1000; | |
) x | |
where st.id = x.id and st.date = x.date |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment