logoalt Hacker News

JamesSwifttoday at 2:16 AM3 repliesview on HN

UUIDs also have a nice benefit of it being impossible to query the wrong table with one if you mixup what an FK goes to


Replies

pyuser583today at 2:49 AM

Yeah this is nice - also helps with grepping dump files.

mamcxtoday at 4:30 AM

How is this done?

show 4 replies
chrismorgantoday at 9:54 AM

You can achieve this with numeric sequences too, by having a consistent step and unique offset in all your sequences. For example, if you will never exceed 16 types, reserve four bits as the type discriminant. (You don’t have to use powers of two, but it may be convenient.)

All sequences use step 16.

Type A has discriminant/offset 0, yielding IDs {0, 16, 32, 48, 64, …}.

Type B has discriminant/offset 1, mapping to IDs {1, 17, 33, 49, 65, …}.

All the way up to Type P with discriminant/offset 15 and IDs {15, 31, 47, 63, 79, …}.

This is also trivially invertible so that you can determine the type from the ID.

A more common approach is to make IDs opaque strings and put a type prefix—A0, B12, P34, that kind of thing. But this way you can keep it as a number, if you wish.