How RandomBlob() Works in SQLite

The SQLite randomblob() function returns a blob containing pseudo-random bytes.

The number of bytes is determined by its argument. If its argument is less than 1 then a 1-byte random blob is returned.

Example

Here’s an example to demonstrate.

SELECT randomblob(8);

Result:

randomblob(8)
-------------
EqƋy      

Generate a GUID

You can use randomblob() in conjunction with the hex() function to generate a globally unique identifier (GUID) by doing the following.

SELECT hex(randomblob(16));

Result:

6A70117D7C25523E0AF82C89D2A0A602

Note that a GUID, also known as a universally unique identifier (UUID), is 128 bits (16 bytes). Therefore, you need to specify 16 as the argument if you want to generate a true GUID.

There’s nothing to stop you from generating a value with more or less bytes.

You can also use the lower() function if you need the GUID to use lowercase letters.

SELECT lower(hex(randomblob(16)));

Result:

50ecfe91179900a8e8cdc583ad5a7658