// conversion reference

SQL UUID function

SELECT UUID() returns a 36-character version 1 UUID. It is unique, but not random: the timestamp and node part can be read back out of the value.

Категория
Conversion
Returns
text (UUID string)
In this category
31 of 39

Синтаксис

UUID()

Поддержка движка

ДвижокSupportЗаметки
SQL Server Different name or syntax NEWID() is the equivalent (v4)
PostgreSQL Different name or syntax gen_random_uuid() / uuidv4(); uuidv7() on 18+
MySQL Да Supported under this name.
SQLite Different name or syntax uuid() only in the sqlite3 shell; randomblob(16) in the library
Oracle Different name or syntax UUID() from 23ai release update 23.9 returns a v4 RAW(16); SYS_GUID() before

Примеры

MySQL

SELECT UUID() AS id;

MySQL

SELECT BIN_TO_UUID(UUID_TO_BIN(UUID())) AS round_trip;

Полезно знать

  • UUID() is version 1: a timestamp plus a node id (a MAC address or random bytes). Because the low time bits come first in the string, the text form does not sort by creation time.
  • Store UUIDs as BINARY(16) with UUID_TO_BIN, not CHAR(36): 36 characters per indexed row adds up, and UUID_TO_BIN(u, 1) can swap the time halves for index locality.
  • Statement-based replication does not reproduce UUID() values; MySQL switches to row-based logging for statements that call it under MIXED, and flags it unsafe under STATEMENT.

Questions about UUID

UUID or auto-increment for keys?

UUIDs generate anywhere (no central counter) and merge cleanly; auto-increment is smaller, sequential and index-friendly. For hot insert tables, prefer BIGINT or time-ordered UUIDs.

Why is my UUID index slow?

CHAR(36) keys are large, and the v1 text form puts the fastest-changing time bits first, so inserts land all over the B-tree. UUID_TO_BIN(UUID(), 1) moves the time-high bits first and stores 16 bytes.

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.