Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql delete old rows on a rolling basis?

Tags:

postgresql

I want to delete rows on one my tables that are more than 7 days old. What is the best way to do this? to make a cron job that runs every night or does PostgreSQL have built in features for doing something like this?

like image 225
Arya Avatar asked Aug 12 '13 12:08

Arya


People also ask

How do I purge old data in PostgreSQL?

PostgreSQL does not currently have a built-in cron-like functionality, so I'd use the system's cron to run a suitable delete statement. If you already have a btree index on the timestamp column, you might as well run the delete much more frequently than nightly, taking out small chunks at a time.

How do I delete multiple rows in PostgreSQL?

First, specify the table from which you want to delete data in the DELETE FROM clause. Second, specify which rows to delete by using the condition in the WHERE clause. The WHERE clause is optional. However, if you omit it, the DELETE statement will delete all rows in the table.

What is Postgres cascade delete?

In PostgreSQL, a cascade means that a delete or update of records in a parent table will automatically delete or update matching records in a child table where a foreign key relationship is in place.

Can we use dapper with PostgreSQL?

Dapper is useful for querying different types of RDBMS, not only PostgreSQL.


2 Answers

delete from the_table where the_timestamp < now() - interval '7 days' 
like image 54
Clodoaldo Neto Avatar answered Sep 30 '22 20:09

Clodoaldo Neto


PostgreSQL does not currently have a built-in cron-like functionality, so I'd use the system's cron to run a suitable delete statement. If you already have a btree index on the timestamp column, you might as well run the delete much more frequently than nightly, taking out small chunks at a time. If you don't have the index, then running it nightly during off-peak times would be better.

If these don't have the performance you need, you could try partitioning. But I'd do that as a last resort, not a first resort.

like image 30
jjanes Avatar answered Sep 30 '22 21:09

jjanes