43

I want to update a field with the current timestamp whenever the row is updated.

In MySQL I would do, when declaring the table

LastUpdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP

But the "on update" part does not work with SQLite. I could not find a way to do it automatically, do I need to declare a trigger?

EDIT: For the record, here is my current trigger:

CREATE TRIGGER [UpdateLastTime]
AFTER UPDATE
ON Package
FOR EACH ROW
BEGIN
UPDATE Package SET LastUpdate = CURRENT_TIMESTAMP WHERE ActionId = old.ActionId;
END

Thanks

5
  • 4
    To SQLite experts: don't be shy to post "you must write a trigger" if that's the answer. Commented Jul 5, 2011 at 6:54
  • 4
    If you're wondering where ActionId and old.ActionId come from, ActionId is a column in Jonas' Package table, and old is defined by SQLite as a reference to the updated rows. (See: sqlite.org/lang_createtrigger.html)
    – Arel
    Commented Jul 9, 2014 at 20:36
  • 1
    I don't know if something has changed in the meantime (SQLite 3.31 here), but neither aMarCruz's solution nor Jixter's one seem to work for me. The first one doesn't fire the trigger ; the last one doesn't prevent recursion: it just (hopefully) ends at some point when CURRENT_TIMESTAMP reachs the next second. This may or may not happen before the SQLITE_MAX_TRIGGER_DEPTH is reached, depending on how fast is the update. Trying it on :memory: database, I was able to get a 'too many levels of trigger recursion' message. The only viable solution seems to be the Dmitrij's one. Commented Jun 2, 2020 at 16:54
  • The solution posted as an edit to the question works for me Commented Sep 1, 2022 at 14:26
  • I recommend using UPDATE OF for all columns but the one holding the date. Ther will be no recursion and the sytnax is simple. See sqlite-triggers
    – DrMarbuse
    Commented Aug 1, 2023 at 8:06

5 Answers 5

31

Yes, you'd need to use a trigger. (Just checking: is your posted trigger working correctly? At first glance, it looks fine to me.)

MySQL's ON UPDATE CURRENT_TIMESTAMP is a pretty unique, single-purpose shortcut. It is what it is; this construct cannot be used similarly for any other values or for any column types other than TIMESTAMP. (Note how this functionality is defined on the TIMESTAMP type page instead of the CREATE TABLE page, as this functionality is specific to TIMESTAMP columns and not CREATE TABLE statements in general.) It's also worth mentioning that while it's specific to a TIMESTAMP type, SQLite doesn't even have distinct date/time types.

As far as I know, no other RDBMS offers this shortcut in lieu of using an actual trigger. From what I've read, triggers must be used to accomplish this on MS SQL, SQLite, PostgreSQL, and Oracle.


One last note for passersby:

This is not to be confused with ON UPDATE clauses in relation to foreign key constraints. That's something entirely different, which likely all RDBMSs that support foreign key constraints have (including both MySQL and SQLite).

4
16

John is correct about the default SQLite settings, this trigger leads to an infinite loop. To avoid recursion, use the WHEN clause.

Following will work even if the recursive_triggers setting is on:

PRAGMA recursive_triggers=1;     --- test

CREATE TRIGGER [UpdateLastTime]
    AFTER UPDATE
    ON package
    FOR EACH ROW
    WHEN NEW.LastUpdate < OLD.LastUpdate    --- this avoid infinite loop
BEGIN
    UPDATE Package SET LastUpdate=CURRENT_TIMESTAMP WHERE ActionId=OLD.ActionId;
END;
5
  • This question was posted almost 4 years ago. Maybe things have changed. It worked fine back then. Commented Mar 17, 2015 at 9:14
  • 4
    Should WHEN NEW.LastUpdate < OLD.LastUpdate be WHEN NEW.LastUpdate = OLD.LastUpdate instead? Since we want the trigger to run when the value hasn't changed.
    – Danny Guo
    Commented Jul 6, 2020 at 18:40
  • 1
    I needed to replace < with = (otherwise the trigger never runs).
    – lonix
    Commented Jan 2, 2022 at 5:13
  • Im pretty sure it intended to be = yes, but this could also theoretically send it into a loop if two updates happen at the same time, though it would exit once the second changes. Commented Jun 3, 2023 at 14:17
  • after looking over the Sqlite docs, this answer does indeed have an infant loop if recursion is enabled, even with the = fix. Commented Jun 3, 2023 at 14:36
4

This one is old, but I ran into this when trying to auto update SQLite like all. The proposed solutions helped, but still need a fix. Here it goes:

CREATE TRIGGER [UPDATE_DT]
    AFTER UPDATE ON table_name FOR EACH ROW
    WHEN OLD.field_name = NEW.field_name OR OLD.field_name IS NULL
BEGIN
    UPDATE table_name SET field_name=CURRENT_TIMESTAMP WHERE unique_field=NEW.unique_field;
END;


Explaining:

  • OLD and NEW are "temporary" instances used by the server, between stored (old) and to-be-updated (new) data
  • WHEN must compare with = in order to run when updating all data except the updated_field_name value... and must accept manual updates of the field itself without entering an infinite loop
  • Then WHEN also needs to happen in case the field was never set, so the IS NULL clause, because the = is not enough
  • Once the trigger is AFTER UPDATE, the WHERE needs to find the updated registry from the NEW unique or primary key, because even keys can be updated ;-)
2

There is more efficient, nice and clean way to do it, for example:

-- List all required fields after 'OF' except the LastUpdate field to prevent infinite loop
CREATE TRIGGER UpdateLastTime UPDATE OF field1, field2, fieldN ON Package
BEGIN
  UPDATE Package SET LastUpdate=CURRENT_TIMESTAMP WHERE ActionId=ActionId;
END;

The code like this one has been tested in my project. Deep sqlite trigger explanation can be found here https://www.sqlite.org/lang_createtrigger.html

1
  • 4
    I'm not sure if something has changed, but for me, this solution sets LastUpdate on EVERY row when any row is updated. It works as expected if I replace the where clause to WHERE ActionId=NEW.ActionId.
    – andyvanee
    Commented Oct 14, 2020 at 18:07
-3
-- Describe UPDATELASTTIME  
CREATE TRIGGER [UpdateLastTime]  
    AFTER   
    UPDATE  
    ON test
    FOR EACH ROW   
    WHEN NEW.last_update_ts <= OLD.last_update_ts  
BEGIN  
    update test set last_update_ts=CURRENT_TIMESTAMP where id=OLD.id;  
END  

-- Describe TEST  
CREATE TABLE "main"."test" (  
    "id" INTEGER PRIMARY KEY AUTOINCREMENT,  
    "name" TEXT,  
    "last_update_ts" DATETIME DEFAULT CURRENT_TIMESTAMP  
);  
2
  • 5
    I'm not going to downvote you, but I don't think this cuts it here. There is no text explanation, and the answer you gave is for MySQL not SQLite, which is what help is being asked for. (Yes, the original presented a MySQL example, but he/she is looking for Sqlite help)
    – Cameron
    Commented Feb 22, 2021 at 0:16
  • Cameron, sorry. The code was written and tested in SQLite at the beginning of 2017, I don't know if it works in current versions, I no longer use SQLite. By the way, I almost don't enter SO anymore, it seems like a "I'm the coolest" contest and the truth is I don't care about the votes, but thank you very much for your attention.
    – aMarCruz
    Commented Dec 3, 2023 at 17:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.