Andreas Andreas - 5 months ago 76
SQL Question

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.

Answer

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 UPDATE
    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 UPDATE
    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.

Comments