thojanssens1
Sorting DB entities having UUIDs
I insert a list of entities in the DB, say articles, for a user. Primary keys are UUIDs.
To sort the articles just as they were initially sent through the List, I tried to sort on inserted_at. It doesn’t work because these records all have the same value for inserted_at, as they were inserted at the same time.
I might have two options:
-
Use microseconds? If I insert that collection of articles, will the timestamp in
inserted_atbe guaranteed to have different microseconds? -
Add an auto-incremented field if the microsecond precision would be a bad idea?
Most Liked
LostKobrakai
There’s also http://gh.peabody.io/uuidv6/ as an alternative to ULID, but again it’s only proposed but not yet an officially accepted standard.
Generally however I’d suggest not needing to sort by (only) the primary id. You’re talking about articles. Articles usually have a published at date(time), so sorting should happen by that. To achieve a stable sort you can use the primary id as secondary sorting column.
fuelen
You can simply use ordering by multiple columns: [:inserted_at, :id]. If inserted_at column is the same then ordering by id will be applied, so you will always have strict order.
al2o3cr
Something to consider: the order of these things sounds important. Is it possible to update that order after inserting the records? Consider materializing that order with something like a position column.
QuinnWilton
I don’t know your exact use case, but ULIDs could be worth looking into as an alternative to UUIDs. They’re essentially lexicographically sortable UUIDs that embed both a Unix timestamp and random data.
You still only get millisecond precision, but you end up with a stable ordering over them because of the random segment.
QuinnWilton
ULIDs are a relatively new idea, and library support isn’t great in all languages. You also do leak timing info through the ULID, which isn’t always desirable.
There may be other drawbacks, but I’m not an expert, sorry.







