port5432
port5432

Reputation: 6401

Why have created_at and updated_at?

Many programming frameworks will automatically populate 2 fields to a model / table / collection. In Rails the two fields are created_at and updated_at. The function of the fields is self-explanatory.

created_at

The timestamp when the record was first created in the database.

updated_at

The timestamp of the most recent change to any of the data stored in the table.

I am working on a Meteor project which does not come out of the box with these fields, and so added createdAt and updatedAt in my project.

Then I began thinking: under what circumstances would we need to know when a record is first created, isn't the last updated enough?

Upvotes: 3

Views: 8340

Answers (3)

basiam
basiam

Reputation: 1567

  • to be able to sort records by latest/oldest
  • to be able to display information about the object (like user asked 10 mins ago)
  • to be able to analyze data (for example to check at what time questions are being asked)
  • it's super helpful when you want to track/debug/audit what's happening in our system

.. and more. Of course, it's possible that your record don't need it now, but it's always better to save this info, since you won't have a simple way to come up with it later if you don't save it now.

Upvotes: 11

Haspemulator
Haspemulator

Reputation: 11308

Not every table need those. If you don't have a clear use case, don't add those. Your database and application will take additional performance hit from calculating, storing and reading them, for nothing.

Upvotes: 5

Shadwell
Shadwell

Reputation: 34774

I think there are a lot of situations where you'd want to know when something is first created.

Just taking stackoverflow as an example:

Knowing when a question was asked is important. If you asked this question two years ago and then edited it yesterday it is very different from your having asked it yesterday.

Knowing when a question was answered is important. Think of some of the badges. "Curious: Ask a well-received question on 5 separate days, and maintain a positive question record.". What if someone retags all my questions which triggers the updated_at to be set to today. I've then gone from asking questions on different days to them appearing to be answered on the same day.

Those are just two examples. The general answer is: whenever you want to know when an object first existed in your system you want created_at. Especially if you're then going to be updating that object.

Upvotes: 3

Related Questions