Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does sqlite3 support a trigger to automatically update an 'updated_on' datetime field?

Tags:

sql

sqlite

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?

like image 572
lightly_recruited Avatar asked Dec 26 '09 20:12

lightly_recruited


People also ask

Does SQLite support triggers?

At this time SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence explicitly specifying FOR EACH ROW is optional.

Does SQLite update?

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.

What does SQLite update return?

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.


2 Answers

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;
like image 75
GDavoli Avatar answered Sep 18 '22 13:09

GDavoli


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;
like image 43
Doug Currie Avatar answered Sep 19 '22 13:09

Doug Currie