I have a requirement to insert new records and delete this record 3 months after created date.
I will create a new table.
I want that query will create the table as well as auto delete the records which are more than 3 months of the created date.
Question posted in PostgreSQL
The official documentation can be found here.
The official documentation can be found here.
2
Answers
You should set cron jobs on your server this is best approach.
This sounds like a maintenance task – already suggested cron job would typically be the most suitable.
If you’re free to use extensions – consider pg_cron:
Otherwise, save your script to a file and feed it to a regular
cron
jobThere’s also the topic of how strict your rules are:
If the records can be 3 months old, +/- 1 day, the daily cron/pg_cron jobs will suffice. The lower your tolerance, the more often your cron will have to keep repeating the cleanup. At some point it might get impractical if it’s effectively running all or most of the time. It could get to a point when next cleanup tasks start before previous ones finish, resulting in a growing queue.
If you absolutely can’t afford to be in possession of records older than 3 months but it’s tolerated when you already delete stuff that’s one day away from the 3 month mark, you can change the cron job to delete records a day earlier
-('3 months'::interval-'1 day'::interval)
If you are allowed to be in possession of those records, just no longer allowed to show outdated records – hide the table behind a view that’s filtering out everything older than exactly 3 months. Demo:
This gives you the highest precision at no maintenance expense. It’s guaranteed to hide records from 3 months ago and older, as of query time – that’s 3 months exactly, down to fractions of a second. You can keep this perceived precision while following the 3 month restriction a bit less strictly, running the clean up task using
cron
,pg_cron
or even triggers, less often.If you can’t have records older than exactly 3 months and you must hold records younger than exactly 3 months, you might want to set up a trigger/rule that will
NOTIFY
on a channel about incoming records and their scheduled deletion times, and a daemon that canLISTEN
on that channel and sets up anat
task (schtasks
on Windows).The script can be a regular
delete
that’s just triggered at the time coinciding with the moment some records become outdated, but still has to search them all and find those, or you can save their primary keys in the cleanup command or let itpop()
it off a FIFO queue somewhere.How long is "3 months"
If you mean 90 days, you need to accept that the deletion dates will shift around based on month lengths within that 90-day difference from creation date.
If you mean 3 months, you need to accept that it’ll sometimes be longer or shorter:
And that it’s interpreted differently by different systems and people: ‘N months’ interval literal in PostgreSQL:
In bash,
at
understands it differently: