Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create trigger for SQLite, when new record is inserted, to delete old records

I have the table "log" in an SQLite database, where I write all my log files.

However I want to pretend the database from getting to big - and the smartest way in doing this, is by using a trigger on the insert command - at least I think so...

When a new record is inserted, a trigger shall get fired, that deletes all records older than 10 days.

Or...

When a new record is inserted, a trigger shall get fired, that deletes all old records, which exceed a specific amount (for example 1000).

I need an example code.

Kind Regards, and thx.

like image 252
Andreas Avatar asked Jan 20 '14 13:01

Andreas


People also ask

Can I create CTE in trigger?

Common table expression are not supported for statements inside of triggers.

What is the use of new and old keyword in trigger?

About OLD and NEW PseudorecordsFor an INSERT trigger, OLD contains no values, and NEW contains the new values. For an UPDATE trigger, OLD contains the old values, and NEW contains the new values. For a DELETE trigger, OLD contains the old values, and NEW contains no values.


1 Answers

This will create an insert trigger that will delete anything with a create date that is more then 10 days old.

CREATE TRIGGER [TRIGGER_NAME] AFTER INSERT ON my_table
BEGIN
    DELETE FROM LOG WHERE DATE(CREATE_DATE) > DATE('now', '-10 days');
END

If you want to do something based on size like you were saying with 1000 rows you can do something like this.

CREATE TRIGGER [TRIGGER_NAME] AFTER INSERT ON my_table
BEGIN
    DELETE FROM LOG WHERE ROW_NO NOT IN 
        (SELECT TOP 1000 ROW_NO FROM LOG ORDER BY CREATE_DATE DESC);
END

This will select the 1000 newest rows and delete anything that is not in that select statement.

like image 127
Smeghead Sev Avatar answered Oct 01 '22 18:10

Smeghead Sev