til icon indicating copy to clipboard operation
til copied to clipboard

Last Updated Columns With Postgres

Open xluffy opened this issue 5 months ago • 0 comments

For MySQL, the ON UPDATE clause can be used to set the current timestamp when a row gets updated. Postgres does not support this feature, unfortunately. If you search for a solution, most folks suggest defining an ON UPDATE trigger for setting the update timestamp. This also is what I’d have done until recently; it works, but having to declare such a trigger for every table can quickly become a bit cumbersome.

But as I’ve just learned from a colleague, there’s actually a much simpler solution: Postgres lets you explicitly set a field’s value to its default value when updating a row. So given this table and row:

UPDATE
  movie
SET
  viewer_rating = 9.6, updated_at = DEFAULT
WHERE
  id = 1;

https://www.morling.dev/blog/last-updated-columns-with-postgres/

xluffy avatar Aug 27 '24 02:08 xluffy