Add the row insertion time to a MySQL table

This article is a part of my "100 data engineering tutorials in 100 days" challenge. (92/100)

It is a good practice to track when the data was inserted into a database or modified. However, relying on the backend applications to set that information correctly is error-prone. That’s why we can configure a MySQL table to automatically use the current timestamp as the default value and store that time as the row creation time.

We have to do that when the table is created (or alter an existing table):

1
2
3
4
create table table_name (
    ...
    created_ts   timestamp default current_timestamp
);

Similarly, we can track the table update time. In this case, we have to use the on update clause:

1
updated_ts   timestamp default current_timestamp on update current_timestamp

Did you enjoy reading this article?
Would you like to learn more about software craft in data engineering and MLOps?

Subscribe to the newsletter or add this blog to your RSS reader (does anyone still use them?) to get a notification when I publish a new essay!

Newsletter

Do you enjoy reading my articles?
Subscribe to the newsletter if you don't want to miss the new content, business offers, and free training materials.

Bartosz Mikulski

Bartosz Mikulski

  • Data/MLOps engineer by day
  • DevRel/copywriter by night
  • Python and data engineering trainer
  • Conference speaker
  • Contributed a chapter to the book "97 Things Every Data Engineer Should Know"
  • Twitter: @mikulskibartosz
Newsletter

Do you enjoy reading my articles?
Subscribe to the newsletter if you don't want to miss the new content, business offers, and free training materials.