Menu

1 / 5

How to Auto-Update an updated_at Column: MySQL ON UPDATE vs a Database Trigger vs the ORM

DEV Community: postgres·Son Tran·about 22 hours ago
#ekQflRWK
#devtopostgresql#devto#dev#column#updated_at
Reading 0:00
15s threshold

Disclosure: I build Schemity , a desktop ERD tool - this post is from our blog and uses it for the examples.

TL;DR: A DEFAULT CURRENT_TIMESTAMP fills updated_at only once, at insert. On MySQL, add ON UPDATE CURRENT_TIMESTAMP to the column; on PostgreSQL, SQL Server and SQLite, write a trigger; or let the ORM set it, which works on every database but misses every write that does not go through the ORM. Pick the database side when scripts, admins or other services write to the table, and the ORM side when only one application does.

Whether updated_at should be set by the database or by the ORM comes down to one question: does anything besides your application write to the table? The database side means MySQL's ON UPDATE CURRENT_TIMESTAMP column clause or a trigger everywhere else; the application side means Rails timestamps, Django's auto_now , Eloquent or Prisma's @updatedAt .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.