I have a table that looks like this
user_id | name | created_on | updated_on
--------------------------------------------------
1 | Peter D | 1/1/2009 |
If I insert or update a record, I'd like a trigger to update the updated_on field with datetime('now'). But I can't find the function name to target the most recently updated row in sqlite3. Is there one?
At this time SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence explicitly specifying FOR EACH ROW is optional.
Introduction to SQLite UPDATE statement First, specify the table where you want to update after the UPDATE clause. Second, set new value for each column of the table in the SET clause. Third, specify rows to update using a condition in the WHERE clause. The WHERE clause is optional.
Returning records modified by the UPDATE command By default, SQLite does not show the number of rows impacted by an UPDATE statement. However, SQLite added the RETURNING clause modelled after PostgreSQL in version 3.35. 0 . This clause causes the commands to return all or part of the records that were modified.
You can specify a trigger to update the updated_on
column of your row when the row changes, however, the change invokes the same trigger again and you'll end up with the error too many levels of trigger recursion
.
In order to avoid that, you can specify which columns you want the trigger to fire upon and of course you need to exclude updated_on
.
CREATE TRIGGER your_table_trig
AFTER UPDATE OF ID,
user_id,
name,
created_on ON your_table
FOR EACH ROW BEGIN UPDATE your_table
SET updated_on = DATETIME ('NOW')
WHERE rowid = new.rowid ; END;
CREATE TRIGGER your_table_trig AFTER UPDATE ON your_table
BEGIN
update your_table SET updated_on = datetime('now') WHERE user_id = NEW.user_id;
END;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With