Quantcast
Viewing all articles
Browse latest Browse all 207

Postgres: Delete but keep x amount of rows per input

Let's say I have the following table, with data:

+----+------+--------+------+| Id | User |  Item  | Time |+----+------+--------+------+|  1 |    1 | Banana | D+1  ||  2 |    1 | Banana | D+2  ||  3 |    1 | Banana | D+3  ||  4 |    2 | Apple  | D+1  ||  5 |    1 | Apple  | D+2  ||  6 |    2 | Apple  | D+3  ||  7 |    2 | Apple  | D+4  |+----+------+--------+------+

New rows are added frequently, so I've decided I need a cleanup job to run on a schedule. (Done via my application code)

In order to not keep too much data, I've decided I want to keep the latest 2 entries, per user and item.

My intended result should look like:

+----+------+--------+------+| Id | User |  Item  | Time |+----+------+--------+------+|  2 |    1 | Banana | D+2  ||  3 |    1 | Banana | D+3  ||  5 |    1 | Apple  | D+2  ||  6 |    2 | Apple  | D+3  ||  7 |    2 | Apple  | D+4  |+----+------+--------+------+

I'm not sure how to accomplish this delete query. Any help would be appreciated, thanks.


Viewing all articles
Browse latest Browse all 207

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>