Interleaving numbers
When you have two numbers that need to be indexed together for speedy lookups there are a variety of mechanisms that can be used, a fast and efficient mechanism is called the Morton Interleave.
A common use case for the interleave is storing a conversation between two users. For example, to retrieve all messages between user 231 and user 119 one would normally query the database with WHERE (sender_id=231 AND receiver_id=119) OR (sender_id=119 AND receiver_id=231)
.
When using an interleave field, you could do something like WHERE conversation_id=48447
. The number 48447 being the interleave, calculated as:
This means faster queries and cleaner code!