// conversion reference

SQL RANDOMBLOB function

SELECT hex(randomblob(16)) makes a 32-character random id. The SQLite library has no UUID function, so this is the usual way to build one.

類別
Conversion
Returns
blob
In this category
35 of 39

語法

RANDOMBLOB(N)

引擎支援

引擎Support備註
SQL Server Different name or syntax CRYPT_GEN_RANDOM(n)
PostgreSQL Different name or syntax gen_random_bytes(n) via pgcrypto
MySQL Different name or syntax RANDOM_BYTES(n)
SQLite 是 the native one
Oracle Different name or syntax DBMS_CRYPTO.RANDOMBYTES(n)

範例

SQLite

SELECT hex(randomblob(16)) AS token;

SQLite

INSERT INTO tokens (value)
VALUES (hex(randomblob(32)));

小知識

  • hex(randomblob(16)) gives 32 hex characters with no version bits and no dashes. The sqlite3 shell's uuid() extension makes real v4 UUIDs, but applications linking the library do not have it.
  • It returns a BLOB: store, compare and index as blob, or hex-encode to text first; comparing a blob to a text literal is a type mismatch that quietly never matches.
  • The twins elsewhere: RANDOM_BYTES (MySQL), CRYPT_GEN_RANDOM (SQL Server), gen_random_bytes (pgcrypto on PostgreSQL) and DBMS_CRYPTO.RANDOMBYTES (Oracle).

Questions about RANDOMBLOB

Is randomblob safe for tokens?

It uses SQLite's internal pseudo-random generator (ChaCha20, seeded from the OS), which is fine for ids and nonces. For long-lived secrets, generate them with the application's OS-level CSPRNG.

Why does my random id repeat?

It should not within realistic lengths: 16 bytes is 128 bits. Duplicates usually mean the value got truncated after hex-encoding; check for substr() or column-width cuts.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.