Skip to content

Instantly share code, notes, and snippets.

@porsager
Last active November 8, 2021 14:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save porsager/59169eaa91e2bf1be0267558ea9dc780 to your computer and use it in GitHub Desktop.
Save porsager/59169eaa91e2bf1be0267558ea9dc780 to your computer and use it in GitHub Desktop.
Remove all but the latest n rows with group by
-- 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
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