TAGS :Viewed: 2 - Published at: a few seconds ago

[ Is the order of model ID's a reliable indication of the order the models were created in? ]

The Scenario

Update: It was brought to my attention that ordering by created_at will actually compare a millisecond float that's of sufficient resolution (by far). However, while I feel a bit dumb now, my question still stands. My scenario is just irrelevant, so I removed it.

The Question

I know that the database knows precisely the order of creation by tracking a row's ID.

Are there any pitfalls in relying on latest ID to determine order?

Answer 1

A better solution is to replace the latest_post_at with something more precise than a second. Time.now.to_f instead of .to_i will give you sub-second precision (millisecond I think, the docs aren't clear). Should two posts happen to have the same millisecond timestamp you could use the id as a tie-breaker.

Answer 2

If you're using whatever is the "natural" way of generating autoincrementing surrogate primary keys for your database, the only pitfall that comes to mind is that the order in which the database sequencer generated the IDs might not be the order in which the transactions that create the Post records start or finish. (Or however you define the time when a post is "created".)

Considering the transaction should normally take a fraction of a second to complete this uncertainty might be irrelevant for your needs.